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

I have two models:

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

and

public class ClassModels
{
    public int ID { get; set; }
    public string Professor { get; set; }
    public decimal Name { get; set; }
}

in my View there is a form to add the class:

@model MvcApp.Models.ClassModels

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ClassModels</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

I would like to add a drop-down menu to the Class View, which lists all the available professors. Professors are in db, and I can easily make a call to db from controller and load all professors in to some list/array.
I need help with how to populate the drop-down with professors using jQuery.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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,

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x