Reputation: 1730
I have an ajax function which works correctly
$.ajax({
type: "POST",
url: urlemp,
success: function (returndata) {
if (returndata.ok) {
// var data = eval("" + returndata.data + "");
select.empty();
$.each(returndata.data, function (rec) {
select.append($('<option>' + returndata.data[rec].Name + '</option>'));
});
select.show('slow');
select.change();
}
else {
window.alert(' error : ' + returndata.message);
}
}
}
);
and in the view I use this selector code
<select id="cmbDept" onload="javascript:cascadingdropdown()">
</select>
Now I would like to change the code of this selector to Razor type like @Html.xxxx How can i do that ?
Upvotes: 0
Views: 1045
Reputation: 28553
try something like this:
public class NamesViewModel
{
public string SelectedName { get; set; }
public IEnumerable<SelectListItem> Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new NamesViewModel();
// TODO: obviously those will come from your database
model.Names = new[]
{
new SelectListItem { Value = "1", Text = "Mary" },
new SelectListItem { Value = "2", Text = "Joan" },
new SelectListItem { Value = "3", Text = "Lisa" },
};
// Preselect the option with Value = "Mary"
// Make sure you have such option in the NAmes list
model.SelectedName = "Mary";
return View(model);
}
}
View (~/Views/Home/Index.cshtml):
@model NamesViewModel
@Html.DropDownListFor(
x => x.SelectedName,
Model.Name,
"Select Name"
)
Upvotes: 1