質問

Information:

I have a list of "Properties" to iterate over, and it seems to ignore iteration (though the iteration works). Honestly I'm not sure what is happening. I've walked through the debugger step by step and it's just mysteriously not working.

My Razor View:

@using (Html.BeginForm()) 
{
    for (Int32 I = 0; I < this.ViewData.Model.Properties.Count; ++I)
    {
        @Html.EditorFor(m => m.Properties._Properties[I], "Property")
    }
}

Property EditorTemplate

@model NMBS.EntityModels.Property

@Html.HiddenFor(p => p.ID)
@Html.LabelFor(p => p.Name)
@Html.HiddenFor(p => p.DataType)
@Html.HiddenFor(p => p.ValueFormat)
@Html.TextBoxFor(p => p.Value.Value)
@Html.HiddenFor(p => p.Value.DataType)
@Html.HiddenFor(p => p.Value.ValueFormat)
<br />

Problem:

The output is as expected except for the values in the controls. They're all the value from m.Properties[0], as I step through the for-loop I check the value of I and it is increasing. m.Properties[0] and m.Properties[1] are different (verified while debugging).

Just to clarify: The EditorFor creates the correct controls but the values are all from m.Properties[0] instead of m.Properties[I]. I does increase with each iteration of the loop though. If I replace the for-loop with @Html.EditorFor(e => e.Properties._Properties) it does the same thing.

Question: Any Ideas why it's outputting incorrect values even though it is iterating correctly?

Edit: After further examination I've noticed that it's trying to put the correct values in the TextBoxFor Value.Value, however the LabelFor Name is incorrect and always showing "Name".

役に立ちましたか?

解決

The problem you're encountering is that LabelFor doesn't write out the value of the property, it writes out a label associated with it. By default, this is simply the property name, but can be overriden using the DisplayAttribute or DisplayNameAttribute on your model property.

In your example above, this will always result in the same value being written out, because it's the same model property in every iteration.

If you want to write out the value of the property, use DisplayFor:

@Html.DisplayFor(p => p.Name)

Or, simply:

@Model.Name
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top