Question

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.

Was it helpful?

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.

OTHER TIPS

I made this into a helper, and have decided to share it in case anyone else comes across this issue.

Helper:

    public static MvcHtmlString CustomHiddenFor(
        this HtmlHelper html, object ListValue,
        string ListName, int ListIndex, string ListItem)
    {
        return MvcHtmlString.Create(
            string.Format("<input type=\"hidden\" value=\"{0}\" name=\"{1}[{2}].{3}\" id=\"{1}_{2}__{3}\" data-val=\"true\"/>", 
                ListValue.ToString(),
                ListName,
                ListIndex,
                ListItem
                ));
    }

Use (note that this is done from a loop where i is the iterator, any value will due in the first spot):

@Html.CustomHiddenFor(Model.W.T.ElementAt(i).TId, "TCs", i, "TId")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top