Return Json of SelectList in asp.net mvc?

4.9k views Asked by At

I'd apreciate if someone could advise on the following:

I have my SelectList in the controller:

 SelectList sl = new SelectList(_unitOfWork.TraumaRepo.GetByType(type).ToList(), "Code", "Name");

Normally my Json returns simple strings:

  return Json(new[]{
                        new { value = "1", text = "item 1" },
                        new { value = "2", text = "item 2" }}, 
                        JsonRequestBehavior.AllowGet);

How can iterate through this SelectList to return its data value and data text fields as JsonResult? How to include foreach or linq into Json()?

In my View I append it to my DropDownList:

    $.each(data, function (value, i) {

                    ddl.append(
                            $('<option/>', {
                                value: i.value,
                                html: i.text
                            }));

                });
2

There are 2 answers

0
OJay On

just get the JSON to serializer the list object directly

  return Json(_unitOfWork.TraumaRepo.GetByType(type).ToList(), 
                        JsonRequestBehavior.AllowGet);
0
ali On