How exactly should a select tag be mapped to an MVC Model variable, I’ve tried everything that I can possibly think of, but every time I check the post method on the controller, the variable that is supposedly binded to the dropdown returns null.
View:
<script type="text/javascript">
var counter = 1;
$('#btnAddLocation').click(function (e) {
e.preventDefault();
$("#tblAddLocation").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($('@Html.LabelFor(m => m.Location)')
)
)
.append($('<td>')
.append($('<select name=Location id=Location' + counter++ + ' class=gradientTextbox>')
)
)
.append($('<td>')
.append($('@Html.LabelFor(m => m.Description)')
)
)
.append($('<td>')
.append($('@Html.EditorFor(m => m.Description)')
)
)
);
$.getJSON("/Locations/GetAllLocations", function (data) {
var items = "<option selected></option>";
$.each(data, function (i, item) {
items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
});
$("#Location" + (counter - 1)).html(items);
});
});
</script>
Controller:
[HttpPost]
public ActionResult ActionName(MyModel model, List<string> Location, List<string> Description) {
return Json(new { success = true });
}
The Description variable in the controller code works fine, but the list for Location returns the right count, but all the items are null.
Any suggestions on how to handle this issue?
Well i figured out the solution.
Html.DropDownListFor version
My version
Noticing the subtle difference, the real issue of the problem lies in this line of the code:
In order to fix my code, the aforementioned line should be replaced with:
Problem fixed. Thanks for the help @Gabe