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 .
2 Answers
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
})
);
});
2 Comments
User279_1
hai darin , i expecting u. My problem is my json not rerun to the client side. Its not trigger in my client side
Darin Dimitrov
You mean the
success callback is not trigerred? Is your controller action called? Are there some errors in your javascript console? Can you see the AJAX request sent in FireBug? Where are you calling this $.ajax method? Is it in a click or submit handler? If so, did you cancel the default action by returning false from this handler to prevent the browser from redirecting away? Is the StudentModel entity JSON serializable (i.e. it does not contain any circular references in its object graph)? Many questions that will help you find the problem.
Userclass looks like