我試圖使用來自Beautiful site和MVC3的Jquery Multiselect插件一起向服務器發送值。如Darrin的example所示,關鍵是創建MultiSelectModelBinder
類,我猜,它會識別從客戶端發送的值,因爲multiselect插件使用[]表示法將所選值發送到服務器。我的aproach有點不同,我填寫dropDownList從我的控制器,而不是模型,保持模型清潔,並且也能夠填充從數據庫列表。我使用Darins示例創建MultiSelectModelBinder
並在Application_Start()
的模型聯編程序中註冊它。我的問題是,我總是不斷收到空模型回我的控制器,這裏是代碼:Mvc3和Jquery Multiselect,發送值到服務器不工作?
MODEL:
public class PersonsSearchModel
{
public string Person { get; set; }
public string Company { get; set; }
//here is my Cities collection
public IEnumerable<string> Cities { get; set; }
}
VIEW:
@model MyNamespace.Model.PersonsSearchModel
@using (Ajax.BeginForm("Search", "Persons", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results",
LoadingElementId = "progress"
},
new { @id = "searchFormPerson" }
))
{
<span>
@Html.TextBoxFor(x => Model.Person, new { @class = "halfWidth"})
</span>
<span>
@Html.TextBoxFor(x => Model.Company, new { @class = "halfWidth"})
</span>
<span>
@Html.ListBoxFor(x => x.Cities, Model.Items, new { @id="combobox1"})
</span>
<input name="Search" type="submit" class="searchSubmit" value="submit" />
}
控制器:
public ActionResult Index()
{
var listCities = new List<SelectListItem>();
listCities.Add(new SelectListItem() { Text = "Select one...", Value = "" });
listCities.Add(new SelectListItem() { Text = "New York", Value = "New York" });
listCities.Add(new SelectListItem() { Text = "Boston", Value = "Boston" });
listCities.Add(new SelectListItem() { Text = "Miami", Value = "Miami" });
listCities.Add(new SelectListItem() { Text = "London", Value = "London" });
ViewBag.Cities = listCities;
return View();
}
public class MultiSelectModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var model = (PersonsSearchModel)base.BindModel(controllerContext, bindingContext);
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[]");
if (value != null)
{
return value.RawValue;
}
return model;
}
}
這裏來自客戶sholud的數據驅動,對接始終爲空?
public PartialViewResult Search(PersonsSearchModel psm)
{
var person = psm.Person;
var company = psm.Company;
var city = psm.Cities.ElementAt(0);
return GetResultPartialView(city);
}
的global.asax.cs
protected void Application_Start()
{
//...
//model binder
ModelBinders.Binders.Add(typeof(IEnumerable<string>), new
FinessenceWeb.Controllers.PersonsController.MultiSelectModelBinder());
}
JQUERY
$("#combobox1").multiSelect();