Wednesday, November 25, 2015

How to change the default Name of a TextBox when using MVC, Razor

We want this format so that each Name on the form is unique. Sometimes we need to change what the value of Name is on the HTML form.

Here is the simple example using @Html.TextBoxFor() to change it from the default of "StartTime" to "MyStartTime":

@Html.TextBoxFor(modelItem => item.StartTime, new { Name = "MyStartTime"})

Below is an example of how to set the Name of the StartTime TextBox when looping through a collection of complex objects such as an Appointment
In the html, the INPUT will have a names like:
Appointments[0].StartTime
Appointments[1].StartTime

The example below formats the Name html property to the format that the MVC binder understands and will automatically create the Appointment objects and bind to them.To better understand how the binding in MVC works, check out this article.

This is possible because @Html.EditorFor takes a parameter for the Name, but @Html.HiddenFor.

If you want to use @Html.TextBoxFor instead, it doesn't have this option, but we can use the htmlAttributes parameter. In this case, Name is CASE SENSITIVE. Using name will not work right.

 @{
        var @i = 0;
    }
    @foreach (var item in Model)
    {
                @Html.EditorFor(modelItem => item.StartTime, "TextBox", "Appointments[" + @i + "].StartTime", null)
                @Html.TextBoxFor(modelItem => item.StartTime, new { Name = "Appointments[" + @i + "].StartTime"})

                 i++;
    }


NOTE: You can also use a for loop instead of the foreach.
NOTE: This technique should also work for the other Html helpers, but I have not tested it.

No comments: