开发者

TryUpdateModel or UpdateModel where Model Has An Array

I have a view model class that looks something like this

public class ViewModel
{
    public string Name { get; set; }
    public IList<SubViewModel> Subs { get; set; }
}

public class SubViewModel
{
    publi开发者_JAVA百科c string Name { get; set; }
    public bool IsSet { get; set; }
    public int Id { get; set; }
}

In my HTML I then have

<%= Html.TextBoxFor(x=>x.Name) %>

<% foreach(var sub in x.Subs) { %>
    <%= sub.Name %> 
    <%= Html.Checkbox("Subs["+index of current sub+"].IsSet",sub.IsSet) %>
<% } %>

In my controller code for a submit of a form surrounding these I do the following

public Save()
{
    var oldModel = GetOldModelFromSession();
    TryUpdateModel(oldModel);
    SaveModelToDb(oldModel);
}

Now when I call try update model it replaces the "Subs" list with a new one rather than just updating the IsSet property at the correct index. Is this possible to have working (I can assume that the oldModel I get is the same as the one originally sent to the page.)


Well, if you accept a FormCollection in the Save method, you can parse that method for each value you are looking for, since that is the collection of values submitted in a post. Or, you can create a new object, use TryUpdateModel to load the values into that object, and only copy over the values you need to the old object.

Or, you can try to replicate TryUpdateModel logic because I don't think you can change that behavior out of the box, but I could be wrong...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜