Fill Select2 dropdown box from database in MVC 4

后端 未结 3 1533
[愿得一人]
[愿得一人] 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:23

    Solved! Finally.

    The full jquery is below, what was needed were two functions to format the returned results from the controller. This is because the dropbox needs some html markup to be wrapped around the results in order to be able to display them.

    Also contractID was needed as an attribute in the controller as without it results were shown in the dropdown, but they could not be selected.

    $("#contractName").select2({
        placeholder: "Type to find a Contract",
        allowClear: true,
        minimumInputLength: 2,
        ajax: {
            cache: false,
            dataType: "json",
            type: "GET",
            url: "@Url.Action("FetchContracts", "Leads")",
            data: function(searchTerm){
                return { query: searchTerm };
            },
            results: function(data){
                return { results: data };
            }
        },
        formatResult: contractFormatResult,
        formatSelection: contractFormatSelection,
        escapeMarkup: function (m) { return m; }
    });
    
    
    function contractFormatResult(contract) {
        var markup = "<table class='contract-result'><tr>";
        if (contract.name !== undefined) {
            markup += "<div class='contract-name'>" + contract.name + "</div>";
        }
        markup += "</td></tr></table>"
        return markup;
    }
    
    function contractFormatSelection(contract) {
        return contract.name;
    }
    
    0 讨论(0)
  • 2020-12-29 00:28

    The problem is that you are returning a List<Contract> 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.

    0 讨论(0)
  • 2020-12-29 00:28

    Select 2 seems to be a standard select with jquery attached so this should work:

    Model:

      public class vmDropDown
      {
        public IEnumerable<SelectListItem> DeviceList { get; set; }
        [Required(ErrorMessage = "Please select at least one item")]
        public IEnumerable<int> SelectedItems { get; set; }
      }
    

    Controller:

     [HttpGet]
        public ActionResult Assign(int id)
        {
          return View(CreateUnassignedModel(id));
        }
    
    [HttpPost]
    public ActionResult Assign(vmDeviceAssign model)
    {
      if (ModelState.IsValid)
      {
        _deviceLogic.Assign(model.GroupId, model.SelectedItems);
        return View("ConfirmDevice");
      }
      else // Validation error, so redisplay data entry form
      {
        return View(CreateUnassignedModel(model.GroupId));
      }
    }
    
    private vmDeviceAssign CreateUnassignedModel(int id)
    {
      return new vmDeviceAssign
      {
        DeviceList = _deviceLogic.GetUnassigned(),
        SelectedItems = null
      };
    }
    

    View:

    <div class="editor-field">
        @Html.ListBoxFor(model => model.SelectedItems, new SelectList(Model.DeviceList, "Value", "Text"))
        @Html.ValidationMessageFor(model => model.SelectedItems)
    </div>
    

    Cant give explanation as am at work but if you leave a message ill pick it up tonight

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