jQuery MultiSelect dropdownlist how to access results?

后端 未结 3 960
陌清茗
陌清茗 2021-01-07 01:06

How can I get the results from a JQUery Multi-select dropdownlist as called per an mvc3/razor?

http://abeautifulsite.net/blog/2008/04/jquery-multiselect/

3条回答
  •  执笔经年
    2021-01-07 01:49

    The multiselect plugin uses the [] notation to send the selected values to the server. As always we start by writing a view model:

    public class MyViewModel
    {
        public IEnumerable SelectedValues { get; set; }
    
        public IEnumerable Items
        {
            get
            {
                return new[]
                {
                    new SelectListItem { Value = "1", Text = "item 1" },
                    new SelectListItem { Value = "2", Text = "item 2" },
                    new SelectListItem { Value = "3", Text = "item 3" },
                };
            }
        }
    }
    

    then a controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    a corresponding view:

    @model MyViewModel
    
    
    
    
    @using (Html.BeginForm())
    {
        @Html.ListBoxFor(x => x.SelectedValues, Model.Items)
        
    }
    

    and finally a model binder associated with the IEnumerable type and which will work with the [] notation used by the plugin:

    public class MultiSelectModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = (MyViewModel)base.BindModel(controllerContext, bindingContext);
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[]");
            if (value != null)
            {
                return value.RawValue;
            }
            return model;
        }
    }
    

    The last part is to register the model binder in Application_Start:

    ModelBinders.Binders.Add(typeof(IEnumerable), new MultiSelectModelBinder());
    

提交回复
热议问题