Hi BugHunter,
Set the model value in hidden field and using the hidden field set the DropDownList selected attribute.
Check this example. Now please take its reference and correct your code.
Model
public class DetailModel
{
public string NoOfYearsSpend { get; set; }
public string NoOfYearsSpendinIndia { get; set; }
public string NoOfYearsSpendOutsideIndia { get; set; }
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
DetailModel model = new DetailModel();
model.NoOfYearsSpend = "20";
model.NoOfYearsSpendinIndia = "15";
model.NoOfYearsSpendOutsideIndia = "5";
return View(model);
}
}
View
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var TotalYears = 50;
for (var i = 1; i <= TotalYears; i++) {
$('<option>', { value: i, text: i }).appendTo("#ddlA");
$('<option>', { value: i, text: i }).appendTo("#ddlB");
}
$('<option>', { value: 51, text: "More Than 50" }).appendTo("#ddlA");
$('<option>', { value: 51, text: "More Than 50" }).appendTo("#ddlB");
var noOfYearsSpendinIndia = $('#hfNoOfYearsSpendinIndia').val();
$.each($("#ddlA option"), function () {
if ($(this).val() == noOfYearsSpendinIndia) {
$(this).attr('selected', 'selected');
return false;
}
});
var noOfYearsSpendOutsideIndia = $('#hfNoOfYearsSpendOutsideIndia').val();
$.each($("#ddlB option"), function () {
if ($(this).val() == noOfYearsSpendOutsideIndia) {
$(this).attr('selected', 'selected');
return false;
}
});
});
</script>
</head>
<body>
<%if (Model.NoOfYearsSpendinIndia != "")
{ %>
<input type="hidden" id="hfNoOfYearsSpendinIndia" value='<%=Model.NoOfYearsSpendinIndia %>' />
<%} %>
<%if (Model.NoOfYearsSpendOutsideIndia != "")
{%>
<input type="hidden" id="hfNoOfYearsSpendOutsideIndia" value='<%=Model.NoOfYearsSpendOutsideIndia %>' />
<%}%>
<select id="ddlA" class="form-control">
<option value="0">--Select--</option>
</select>
<select id="ddlB" class="form-control">
<option value="0">--Select--</option>
</select>
</body>
</html>
Screenshot