views:

35

answers:

1

Hello! For example I have:

<select id="myDropdown" name="myDropdown">
<option value="6">Six</option>
<option value="5">Five</option>
<option value="3">Three</option>
<option value="1">One</option>
</select>

And I have controller:

    DBEntity context = new DBEntity(); // My EntityModel
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetStartValues()
    {
        var b = context.MyTable.ToList();
        return Json(ConvertObj(b));
    }
    private object ConvertObj(List<MyTable> lst)
    {
        var list = new object[lst.Count];
        for (int i = 0; i < lst.Count; i++)
        {
            list[i] = new { value = lst[i].MyValue, name = lst_meals[i].MyText };
        }
        return list;
    }

My question is: How to Init this values as start values using jQuery. I can use solution like this:

    public ActionResult Index()
    {
        var model = context.MyTable.ToList()
        return View(model);
    }

In .aspx

   <select id="myDropdown" name="myDropdown"> 
   <% foreach(var obj in Model.MyTableList) {%>
   <option value="<%: obj.MyValue %>"><%: obj.MyText %></option>
   <% } %>

But I want use Jquery for this)

I want to populate the drop down list by making an asynchronous call to a service, but I don't know what event I have to use... If I trying to populate drop down:

 $(document).ready(function () {
     $.post("/GetStartValues/", { }, function (data) {
       populateDropdown($("#[id*='myDropdown']"), data);
     });
 }

 function populateDropdown(select, data) {
        select.html(''); //clear all items
        $.each(data, function (id, option) {
            select.append($('<option></option>').val(option.value).html(option.name));
        });
 }

But it isn't working. I want to insert values into DropDown using Jquery request as soon as page is loaded.

A: 

Is your controller returning the correct Ajax?

I'm not sure what your ConvertObj does but assuming you are returning the Ajax correctly, then this jQuery should work.

$.ajax({
            url: '/GetStartValues/',
            type: 'POST',
            data: {
            },
            success: function (data) {
                $('#myDropdown').html('');
                for (var i=0; i < data.length; i++) {
                    $('#myDropdown').append($('<option></option>').attr('value', data[0].value).text(data[0].name));
                }
            }
        });
Jeff T
Thank for answer) It works=) (but I use my function to input values into DropDown) function populateDropdown(select, data) {...});Sorry((( I didn't write function ConvertObj. I'll do it in few minutes.
Leonid