Beautiful siteとMVC3のJquery Multiselectプラグインを使用して、サーバーに値を送信しようとしています。ダーリンのexampleに示されているように、キーはMultiSelectModelBinder
クラスを作成することです。マルチセレクションプラグインは[]表記を使用して選択した値をサーバーに送信するため、値がクライアントから送信されることを認識します。私のaproachはちょっと違います、私はdropDownList私のコントローラとモデルではなく、モデルを清潔に保ち、またデータベースからリストを埋めることができました。ダーリンの例を使って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" />
}
CONTROLLER:私の問題は、私はいつも戻って私のコントローラに空のモデルを取得しておくことで、ここのコードです
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からのデータが得られますが、buttは常にnullですか?
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();