Fill Select2 dropdown box from database in MVC 4

后端 未结 3 1561
[愿得一人]
[愿得一人] 2020-12-29 00:08

I need help writing the jquery/ajax to fill a Select2 dropdown box.

For those who don\'t know what Select2 is, it is a javascript extension to provide Twitter Bo

3条回答
  •  半阙折子戏
    2020-12-29 00:28

    The problem is that you are returning a List from that controller method, but the MVC runtime doesn't know how to hand that off to the browser. You need to return a JsonResult instead:

    public JsonResult FetchContracts() 
    {
        TelemarketingContext teleContext = new TelemarketingContext();
        var contracts = teleContext.Contracts.ToList();
        var json = from contract in contracts 
            select new {
                name = contract.ContractName,
                id = contract.ContactID,
            };
        return Json(json, JsonRequestBehavior.AllowGet);
    }
    

    Now, the data param of the AJAX : Success function will be the JSON from the controller. I'm not familiar with how this plugin works, but you should be able to loop through the json in data manually if you need to.

提交回复
热议问题