2

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
  • It entirely depends on what you want to achieve. Is it necessary for you to fill the drop down via ajax (dynamic content)? If the options in your dropdown are static it might be easier to simply populate dropdown on it's creation from list of options provided in view model or even ViewBag. If you could give more details as to how you are going to use the dropdown I could post some examples. – jahu Apr 29 '14 at 08:26
  • Does the above code not work?? – Ashutosh Apr 29 '14 at 08:27
  • Maybe something useful can be found in this question and in answers http://stackoverflow.com/questions/19224550/pass-data-to-view-using-action-c-sharp-mvc – jahu Apr 29 '14 at 08:32
  • I cannot not use viewbag i have a table which display information and on top i want a dropdown list. I know that i have to use ajax to do this. i just want to get data from the database and populate into a dropdown using ajax. let me know if you require more info –  Apr 29 '14 at 08:32
  • Why is your controller method virtual??? – Ashutosh Apr 29 '14 at 08:42
  • @Ash that one of a example i've used. I am not sure what virtual does. –  Apr 29 '14 at 08:47
  • @User911 Does changing your code to @Html.DropDownList("ch_user1"); work. Also remove virtual keyword unless it is required as I don't think it is required in your case. – Ashutosh Apr 29 '14 at 08:50

4 Answers4

2

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));
            });

    });
}
Community
  • 1
  • 1
Shaikh Farooque
  • 2,620
  • 1
  • 19
  • 33
  • what does this do `_repository.GetInformation()` is `_repository` a modal name then what is `GetInformation()`?? –  Apr 29 '14 at 08:36
  • It is just a example. you need to modify it according to your requirement. the important thing is return Json(model, JsonRequestBehaviour.AllowGet); – Shaikh Farooque Apr 29 '14 at 08:39
  • i've used that example but i get an error so i said something like this `var staff = from saf in db.Staff where saf.StaffName select saf;` i am getting an error in this line `saf.StaffName` it says `cannot implicity convert type string to bool` –  Apr 29 '14 at 10:27
  • What is the use of where clause in this example. Just remove the where clause. – Shaikh Farooque Apr 30 '14 at 09:49
0

The code you have shown should work with a simple change-

@Html.DropDownList("ch_user1");
Ashutosh
  • 1,000
  • 15
  • 39
  • how do i set dropdown id to `ch_user1` because right now i am getting an error saying `Additional information: There is no ViewData item of type 'IEnumerable' that has the key 'subjects'` –  Apr 29 '14 at 12:25
0

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);
            });
        });
    });
Community
  • 1
  • 1
Ashwini Verma
  • 7,477
  • 6
  • 36
  • 56
  • I am stuck when creating my dropdown i copied and past same thing i get an error under `@Html.DropeDownListFor` i get read line?? –  Apr 29 '14 at 12:24
  • may be you got error for this line x => x.Id. this should be model property to get selected value. – Ashwini Verma Apr 29 '14 at 12:29
  • my modal name is staff and column name is stafdid and staffName- i am trying to populate staff name so how would that look? –  Apr 29 '14 at 12:32
0

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);
   }
 }); 
Naveen Chandra Tiwari
  • 5,055
  • 3
  • 20
  • 26