4

Problem

I want to display a form that will have a variable amount of values. However each form item has to have a sort of key associated with it. For example, the form generates a name, username and occupation fields, I need to also have keys generated so when the form is submitted, the receiver method can tell what items are what.

Attempted Solution

Right now I have a list of FieldItems where a FieldItem is just a class with one class variable of a String. The solution works when populating the form, however on submission a list is returned and I can not tell which value belongs to which key. I was thinking about using a dictionary but I do not know how this would be accomplished in razor.

View Model

public class BuildReportViewModel
{
    public IList<BuildReportFieldItemViewModel> Fields { get; set; }
}
public class BuildReportFieldItemViewModel
{
    public string Field { get; set; }
}

Editor for BuildReportFieldItemViewModel

@model BuildReportFieldItemViewModel

<div class="editor-label">
    <label for="@Model.Field">@Model.Field</label>
</div>
<div class="editor-field">
    <input type="text" name="@Model.Field">
</div>

1 Answer 1

4

Try using a hidden key field

View Model

public class BuildReportViewModel
{
    public IList<BuildReportFieldItemViewModel> Fields { get; set; }
}
public class BuildReportFieldItemViewModel
{
    public string Field;
    public string Key;
}

Editor for BuildReportFieldItemViewModel

@model BuildReportFieldItemViewModel

<div class="editor-label">
    <label for="@Model.Field">@Model.Field</label>
</div>
<div class="editor-field">

    @Html.TextBoxFor(x => x.Field)
    @Html.Hidden(Model.Key, "key_value");
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

probably best solution. You could use a GUID for your key since it isn't associated to any other data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.