Dynamically populate the drop-down using jQuery in ASP.Net MVC3

后端 未结 2 984
抹茶落季
抹茶落季 2020-12-04 01:05

I have two models:

public class ProfessorModels
{
    public string FullName { get; set; }
    public int ID { get; set; }
}

and

         


        
相关标签:
2条回答
  • 2020-12-04 01:23

    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:

    <select id="info"></select>
    

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

    This assumes that Id and Name are properties of your object. You could use ID and FullName depending on which drop down you're loading. I also use T4MVC to get the different method names.

    Hope this helps,

    0 讨论(0)
  • 2020-12-04 01:30

    Have an action method which returns a List of Proffessors

    public ActionResult GetProfessors()
    {
      var professorList=repo.GetProfessors(); //get list of professor object
      return Json(professorList,JsonRequestBehavior.AllowGet);
    }
    

    Now in your View, Have a DropDown

    <select id="listProfessors"></select>
    

    Use jQuery ajax to load the data to this element on the document ready event. Add the below script in your view.

    <script type="text/javascript">
      $(function(){
        var items="";
        $.getJSON("@Url.Action("GetProfessors","YourControllerName")",function(data){
    
            $.each(data,function(index,item){
               items+="<option value='"+item.ID+"'>"+item.FullName+"</option>";
            });
            $("#listProfessors").html(items);
        });
    
      });    
    </script>
    

    Assuming your Controller name is YourController and you have jQuery loaded into this page properly.

    0 讨论(0)
提交回复
热议问题