Reputation: 50
I am using jquery to populate a dropdown list in ASP.NET MVC
$(function () {
$.getJSON('/GetFoo', function (result) {
var ddl = $('#foo');
ddl.empty();
$(result).each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Text)
.appendTo(ddl);
});
});
});
Here's the controller action that return the JSON used in that process:
public ActionResult GetFoo()
{
ViewBag.IdTable = new SelectList(db.Table, "IdTable", "Description");
return Json(ViewBag.IdTable, JsonRequestBehavior.AllowGet);
}
And here's how my dropdown list goes into my view:
@Html.DropDownListFor(model => model.IdTable,Enumerable.Empty<SelectListItem>(), "-- Loading Values --", new { id = "foo" })
To clarify more what I'm doing, I want to show the Description in the select list options instead of the IdTable.
Everything works just fine until the moment I validate my dropdown list choice. In fact, it gives the following error:
The value [Choice] is not valid for IdTable.
So I guess the values of the select list options are set to the Description field, rather than the Id field.
How can I fix that?
Upvotes: 1
Views: 55
Reputation: 14741
Try this:
public ActionResult GetFoo()
{
return Json(db.Table.Select(x=> new { Id = x.IdTable, Text = x.Description}),
JsonRequestBehavior.AllowGet);
}
Or in your JS change
.attr('value', this.Id)
to
.attr('value', this.Value)
Upvotes: 1