asp.net-mvc-3html.hiddenfor

Use Html.HiddenFor while iterating


The ViewModel looks like this:

public W { get; set; }
public WC WC { get; set; }
public List<TC> TCs { get; set; }

WC has a correlated group of TC. Their relation is mapped by TC containing the foreign key WCId.

In the view, I have a form. In the form, there are input fields for WC. Then, there is a group of TC depending on a count with a max of 4. Each TC has a related T in that TC has a foreign key TCId. I am trying to make sure that when the form is posted TC has the correlating TId. The TId is held in a list of T in W (i.e. @Model.W.T.ElementAt(someindex).TId).

How can I levarage a lambda expression to use the helpers to generate this relation in the view so it can be consumed in a httppost action by the correlating controller?

Here is what I am doing right now:

<input type="hidden" value="@(Model.W.T.ElementAt(i).TId)"
 name="TCs[@(i)].TId" 
 id="TCs_@(i)__TId" data-val="true"/>

What I would like to do is use the @Html.HiddenFor helper but cannot seem to get it to work so I just used the slightly dynamic yet still hardcoded approach above. Note: this works, however, I would like it to be cleaner.


Solution

  • What you're doing right now is -as far as I know - the only way to do it. I don't know of a way for a simpler @Htm.HiddenFor(...) version. I've been dealing with similar issues too. Nevertheless, if you think that you could reuse the pattern above you can still create your own Display/Editor template or other more abstract ways. Of course they'll be more verbose and complex than your "ugly" but straight forward approach.