Niranjan Godbole Niranjan Godbole - 8 months ago 36
jQuery Question

Unable to bind dropdown in MVC4 Jquery

I am binding dropdown using jquery MVC4. In controller I am getting all the required values but when i put alert in jquery success call,it displays empty. It shows [object,object]. This is what i tried so far.

url: "@Url.Action("getrejectReason", "DocumentVerification")",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function () {
alert(" An error occurred.");
success: function (result) {
$.each(result, function (index, item) {

<select id="options"></select>

This is server side code.

public JsonResult getrejectReason()
DB_KYC3Entities db = new DB_KYC3Entities();
var result = new SelectList(db.dbo_tm_rejectcomment, "Id", "RejectComment");
return Json(result, JsonRequestBehavior.AllowGet);

Can someone tell me what i am doing wrong here? Thanks


Your controller method is passing back a serialized SelectList which contains properties Value and Text (uppercase), so to add the options you need to refer to the same properties (uppercase).


However there are a few other issues with your code.

  1. Your not sending any data in the request, so contentType: "application/json; charset=utf-8", is unnecessary
  2. Your method is marked [HttpPost], so using JsonRequestBehavior.AllowGet is unnecessary
  3. You should only send back data that the view uses (there is no point sending back the additional properties of SelectListItem to the client, so the code in the method should generate a collection of anonymous objects

    var model = db.dbo_tm_rejectcomment
        .Select(x => new { Value = x.Id, Text = x.RejectComment });
    return Json(model);

But your ajax call is unnecessary and your effectively telling the client - here is the view, but I forgot to send all the data, so wait a bit longer and make another request to get it. You should be generating you view using

@Html.DropDownListFor(m => m.SelectedRejectReason, Model.RejectReasonList)

where RejectReasonList is a property in your view model that is IEnumerable<SelectListItem>

As a side note, do not use alert() for debugging. Add debugger; in your script (or set a breakpoint) so that you can step through the script and inspect the variables. If you do want to print the output, use console.log() which would have allowed you to expand the output and see the actual objects in the array.