I have an ASP.NET MVC application. At a certain point I get a FormCollection in a Controller method that I want to use to update a model. In the collection not all of the values are properties of that model and the property to be updated is an item from a list, and that list is also an item from another list. Something like this (I hope this is clear):

propertyToUpdate --> model.Items[0].Subitems[0].SomePropertyClass.Value;

I tried this in my Controller:

UpdateModel(model);

The problem is that this is not working and I assume it has something to do with the fact that the reflection is not working. I went searching and stumbled upon this article. So I understand that using the prefix-parameter solves the problem. But not in my case, as the properties lie "deeper" in the model as items from a list.

Does anyone know how I can solve this?

Update:

Here's the EditorTemplate for the property:

@model Q95.Domain.Property

<li>
    @Html.DisplayFor(p => p.Description) : 
    @Html.DisplayFor(p => p.Quantity.Value)
    @Html.DisplayFor(p => p.Quantity.Unit.Description)
    <br />
    @Html.TextBoxFor(p => p.Quantity.Value)
</li>

This template is called like this:

<ul>
    @Html.EditorFor(model => model.SegmentRequirement.MaterialRequirements[j].Properties)
</ul>

Is this enough code or is there something still missing?

Update2:

Ok, in all the sub-properties I defined parameterless constructors and now I call:

UpdateModel(segmentRequirement, "SegmentRequirement", form.ToValueProvider());

This updates the model, but everything from MaterialRequirements is re-instantiated... :S

有帮助吗?

解决方案

UpdateModel works fine on "Deep properties".
The problem is probably the data in the collection you get isn't equal to the properties names.
Check 3 places to see the values you get from the page

  1. The form values.

  2. The route data

  3. The query string

In exact that order.

The keys should match you model properties names.


Update:
How to match the keys to properties names?
The input id will be the key you will get, change the the ids to match your properties names, or even better, use the HtmlTextBoxFor helper: see this article:

其他提示

Maybe you should create flattened ViewModel and then use that to populate the view, and later synchronize it with the real model.

Can you show us your model and your view, if you are not using htmlhelper, you then have to understand the naming convention very well in order to make the model binding work with your model. so the first thing in first is to show us your model and view.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top