Reputation:
I have a dropdown list and i am trying to populate my dorpdown list with the data from the database, for this i am using mvc so how do i write a method in controller and how do i write the jquery for that: This is what i implemented in my view;
@Html.DropDownListFor("")
This is what i can find for jquery:
$(document).ready(function()
{
$('#id_trial').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
source: "/ClassName/MethodName",
dataType: "json",
success: function (data) {
$.each(data.aaData,function(i,data)
{
alert(data.value+":"+data.text);
var div_data="<option value="+data.value+">"+data.text+"</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
}
});
});
});
This is what i think might be a method in a controller:
public virtual JsonResult MethodName()
{
IList<Fund> funds = _fundManager.Search();
var list = from x in funds
select new { Id = x.Code, Name = x.Name };
return Json(list);
}
I dont know how to link all of them and make it work, ant help will be appreciated.
Upvotes: 2
Views: 5802
Reputation: 7525
Just try below. See this example given by Darin Dimitrov.
@model App.Models.staff
@Html.DropDownListFor(
x => x.staffName,
Enumerable.Empty<SelectListItem>(),
"-- Loading Values --",
new { id = "foo" })
$(function () {
$.getJSON('/ClassName/MethodName', function (result) {
var ddl = $('#foo');
ddl.empty();
$(result).each(function () {
$(document.createElement('option'))
.attr('value', this.stafdid)
.text(this.staffName)
.appendTo(ddl);
});
});
});
Upvotes: 0
Reputation: 5123
Try to do something like this:
$.ajax({
type: "GET",
source: "/ClassName/MethodName",
dataType: "json",
success: function (data) {
var div_data="";
$(data).each(function(){
div_data +="<option value="+$(this).value+">"+$(this).text+"</option>";
});
$('#ch_user1').html(div_data);
}
});
Upvotes: 0
Reputation: 2630
Can refer to following code snip or detail article on following link
Dynamically populate the drop-down using jQuery in ASP.Net MVC3
In your controller:
[HttpGet]
public virtual JsonResult LoadInfo()
{
var query = _repository.GetInformation(); //Here you return the data.
return Json(query, JsonRequestBehavior.AllowGet);
}
Then in your view:
Then you load the drop down using jQuery
function LoadInfo() {
$.getJSON("@Url.Action(MVC.ControllerName.MethodName())", null,
function (data) {
$("#info").empty();
$.each(data, function () {
$("#info").append($("<option />").val(this.Id).text(this.Name));
});
});
}
Upvotes: 2
Reputation: 1050
The code you have shown should work with a simple change-
@Html.DropDownList("ch_user1");
Upvotes: 0