In an HTML form how do you bind jquery controls (e.g. tokeninput) the same way you bind the ordinary primitive types to the model? I am struggling to find ways to do this and I know you can use custom templates etc, but there is nothing for jquery plugins.
Specifically I am using tokenInput see here (http://loopj.com/jquery-tokeninput/).
Here is the jQuery code that I apply against a standard HTML text input. For every keypress it goes to the controller to return a list of authors. You can also pre-populate with authors, and I use the data tags in HTML5 to prepopulate the control.
$("#AUTHORs").tokenInput('/author/getauthors/', {
hintText: "Enter surname",
searchingText: "Searching...",
preventDuplicates: true,
allowCustomEntry: true,
highlightDuplicates: false,
tokenDelimiter: "*",
resultsLimit: 10,
theme: "facebook",
prePopulate: $('#AUTHORs').data('AUTHORs')
});
I have posted a bit of code from my view just to show you exactly what I am trying to bind to the model.
@model myModels.BOOK
@{
ViewBag.Title = "Edit";
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Basic</legend>
<div class="editor-label">
@Html.LabelFor(model => model.TITLE)
</div>
<div class="editor-field" >
@Html.EditorFor(model => model.TITLE)
@Html.ValidationMessageFor(model => model.TITLE)
</div>
<div class="authors">
<div class="editor-field">
<input type="text" id="authors" name="authors" data-val="true" data-val-required="You must enter at least one author" data-authors="@Json.Encode(Model.AUTHORs.Select(a => new { id = a.AUTHOR_ID, name = a.FULL_NAME }))"/>
<span class="field-validation-valid" data-valmsg-for="authors" data-valmsg-replace="true"></span>
</div>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
and here is the code that I use when trying to update the model (after pressing “Save”) on the form:
[HttpPost]
public ActionResult Edit(BOOK book)
{
if (ModelState.IsValid)
{
db.Entry(book).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = book.REF_ID });
}
ViewBag.REF_ID = new SelectList(db.REFERENCEs, "REF_ID", "REF_ID", book.REF_ID);
return View(book);
}
When you look at the code in the HTML it has formatted the authors from the tokeninput element it looks like so, and it seems that this format it has a real problem with I think:
<input type="text" id="AUTHORs" name="AUTHORs" data-val="true" data-val-required="You must enter at least one author" data-authors="
[{"id":156787,"name":"Faure,M."},
{"id":177433,"name":"Wang,D.Z."},
{"id":177434,"name":"Shu,L.Sh"},
{"id":177435,"name":"Sheng,W.Z."}]"
style="display: none; ">
It seems that you are using the tokeninput plugin. Let’s have a step-by-step example about how this could be implemented with ASP.NET MVC:
Model:
Controller:
View:
and the last step is to write a custom model binder which will retrieve the authors form the ids:
that will be registered in Application_Start: