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

Total Post:46

Points:324
.NET  JQuery  Mvc3 
 1115  View(s)
Ratings:
Rate this:
I have a model
public class City
{
    public string Name { get; set; }
    public int ID { get; set; }
}

  1. Post:40

    Points:280
    Re: 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:

    <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 Name depending on which drop down you're loading.
     Hope this helps,

      Modified On Apr-09-2018 01:26:48 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!