MVC3 ModelBinding to a collection posted back with index gaps

好久不见. 提交于 2019-12-19 08:27:49

问题


I have a collection of objects on my Model that I'm rendering in a View by using EditFor function, and I have an EditorTemplate which is responsible for actually rendering each object.

@Html.EditorFor(model => model.MyObjects)

This has worked well for a while now, and when you check the html, my text boxes are prefixed with the model property, followed by the index of the collection they came from.

<input class="text-box single-line" id="MyObjects_2__SomeProperty" 
name="MyObjects[2].SomeProperty" type="Text" value="" />

However I've recently started using the ShowForEdit and ShowForDisplay properties in the model metadata for the collection, and in the first line of my editor template if the ShowForEdit is not true, I just skip it.

@if (!ViewData.ModelMetadata.ShowForEdit)
{
    return;
}

But because these are all indexed in the html, when I try to save this collection back to the viewmodel via a postback, it fails because of a reliance on the indexing numbers. Every item in the collection after the missing index is missing from my view model when I check it's value.

In this case it's actually my first item in the collection that I'm skipping since I don't want it to be visible on the edit view, but because of this when I postback the first index in the html is 1 (instead of 0 like it normally would be), but this is a problem when you try to save the changes. This is also a problem when altering the DOM using javascript.

Has anyone else encountered a problem with the default model binder's ability to read data posted back when one or more indexes in the html represented collection are not present?

Are there model binders that handle this problem?


回答1:


There are some very good blog posts that allow you to modelbind to a list without the need to provide zero based contiguous index. plz have a look at http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
http://zahidadeel.blogspot.com/2011/05/master-detail-form-in-aspnet-mvc-3-ii.html
Furthermore, if you are interested in MVVM pattern and knockout js you can check this great work by steve sanderson
For more reading put "editing varibale length list mvc style" in google and it will give u a dozen useful links



来源:https://stackoverflow.com/questions/6852559/mvc3-modelbinding-to-a-collection-posted-back-with-index-gaps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!