I have a view model witch contains iterative items. I place them in my view via the EditorFor() method.
View:
@model Models.MyModel
@using (Html.BeginForm(@Model.Action, @Model.Controller))
{
<div class="section" id="Terms">
@Html.EditorFor(m => m.Terms)
</div>
<input type="submit" value="Save" />
}
Model:
public class MyModel
{
public IEnumerable<Term> Terms { get; set; }
}
EditorTemplates\Term.cshtml:
@model Models.Term
@if (Model != null)
{
<fieldset>
<legend>Term</legend>
@Html.HiddenFor(model => model.TermID)
<div class="editor-label">
@Html.LabelFor(model => model.Identifier)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Identifier)
@Html.ValidationMessageFor(model => model.Identifier)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
</fieldset>
}
I want to be able to dynamically add / remove items from the list in the view, like this example on knockout.js, but how do I preserve the auto-id's MVC creates??:
http://knockoutjs.com/examples/cartEditor.html
Here are my requirements for this:
- Add new terms
- Remove terms
- validate the new terms views that are added
I've read other questions on SO and I haven't found a real definitive answer on this. Is knockout.js the accepted way to do this? Are there any examples of doing this with Knockout AND MVC?
Thanks!
You want knockout MVC http://knockoutmvc.com/CartEditor
You don't have to use knockout for this, what you really need is javascript with validations and create/delete actions which map onto restful controller actions on the MVC side of things. How you go about implementing that is up to you. Knockout makes it easy though.
I found this post Nested Collection Models in MVC3 by Jarrett Meyer, who has a solution that doesn't use knockout and maximizes code reuse.
This covers both add and delete methods. I'll outline the add method here.
The Model
Views
Helper
Javascript
You need to do following:
Depends on your application as well so knockout is just helping you on client for step 3 where you are creating new from old copy. You can sue JQuery templates for that as well and json2 to serialise with old browser support.
All you need to understand is that once you are on client you have sent your model here once so dont worry about server side. Whatever you build at client side can be send either one model at a time to saveTerm action which retruns json with term id and other info or you can return a collection of saveTerm as a json array and it would work fine.
if you are thinking of sending an array on postBack and not ajax just keep the form element names same and duplicate term input fields and send over. MVC will map them to a array of terms as it does with json.