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/
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());