简体   繁体   中英

how to bind the @html.dropdownlist name with id in mvc using JavaScript formate

I need to bind the @html.dropdownlist in mvc using JavaScript format with name and id . I try but not bind in the JavaScript side its not pass the value in client side. My list value format image is given below. How to pass the value with name and id not serial no .

change the type to GET in your ajax request like

 $.ajax({
 type: 'GET',
 ...

and try

$.each(data, function (index, val) {
    $('<option/>',{value:val.Id,text:val.Text}).appendTo("#MyDdl");
 });

You are sending a SelectList to the client. This class implements IEnumerable<SelectListItem> and SelectListItem has 2 properties: Value and Text which you should bind your drop down to:

$.ajax({
    type: 'POST',
    url: url,
    data: { id : id },
    success: function (data) {
        $('#MyDdl').empty();
        $.each(data, function () {
            $('#MyDdl').append(
                $('<option/>', {
                    value: this.Value,
                    html: this.Text
                })
            );
        });
    }
});

In your example you were using val.Id but there's no such property.

But as a matter of fact you don't need any SelectList. Just return the students collection:

[HttpPost]
public ActionResult Some(string id) 
{
    var students = service.GetAllStudents().ToList();
    students.Insert(0, new StudentModel{ Id = 0, Name = "Select student" });
    return Json(students);
}

and now you can bind your dropdown to the Id and Name properties of this collection:

$.each(data, function () {
    $('#MyDdl').append(
        $('<option/>', {
            value: this.Id,
            html: this.Name
        })
    );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM