Html Helpers in Razor partial view for collections

Viewed 41

I have - again - a case where I need to put a lot of fields in a partial view in order to be able to add dynamically this partial view in a form.

Up to now, I always made my html markup by hand, so the file looks like:

@{
    var collectionId = $"Collection[{Model.CollectionId}].{{0}}";
}

<label for="@(string.Format(collectionId, "FirstName"))">@ApplicationResources.FieldFirstName<span style="color:red"> *</span></label>
<input class="form-control"
        data-val="true"
        data-val-required="@(string.Format(ApplicationResources.Error_Required, ApplicationResources.FieldFirstName))"
        id="@(string.Format(collectionId, "FirstName"))"
        name="@(string.Format(collectionId, "FirstName"))"
        type="text"
        value="@(string.IsNullOrWhiteSpace(Model.FirstName) ? string.Empty : Model.FirstName)" />
<span class="field-validation-valid text-danger"
        data-valmsg-for="@(string.Format(collectionId, "FirstName"))"
        data-valmsg-replace="true"></span>

And it works well:

  • If error in post, I can show back the data - they are not lost
  • I can also display (with edition) previous saved data

But, I have to do all the html markup manually, for every imaginable input type...

So, my question is to know if it is possible to achieve the same html output through @Html helpers (Html.TextBoxFor (or TextBox), DropdownFor, CheckboxFor, ValidationMessageFor etc.), as everything I tested at this point doesn't work for viewmodel's attributes validation?

0 Answers
Related