I have three partial views that are each strongly typed with separate models. Each view contains it's own form and submits to different actions. Some of the models contain properties with the same names and when I use the html helper methods to create the textboxes and labels, I'm ending up with duplicate html ids on the page.
Partial _Residential View
@model MyProject.Models.ResidentialModel
@using (Html.BeginForm("Residential", "Transaction"))
{
@Html.LabelFor(m => m.PersonName)
@Html.TextBoxFor(m => m.PersonName)
@Html.LabelFor(m => m.ReferenceNumber)
@Html.LabelForm(m => m.ReferenceNumber)
<input type="submit" value="Submit" />
}
Partial _Business View
@model MyProject.Models.BusinessModel
@using (Html.Beg开发者_JAVA百科inForm("Business", "Transaction"))
{
@Html.LabelFor(m => m.BusinessName)
@Html.TextBoxFor(m => m.BusinessName)
@Html.LabelFor(m => m.ReferenceNumber)
@Html.LabelForm(m => m.ReferenceNumber)
<input type="submit" value="Submit" />
}
Normal View
<h2>Residential Transaction</h2>
@Html.Partial("_Residential")
<h2>Business Transaction</h2>
@Html.Partial("_Business")
The output that I'm getting looks like the following:
<h2>Residential Transaction</h2>
<form action="/Transaction/Residential" method="post">
<label for="PersonName">Person Name:</label>
<input type="text id="PersonName" name="PersonName" />
<label for="ReferenceNumber">Reference Number:</label>
<input type="text" id="ReferenceNumber" name="ReferenceNumber" />
<input type="submit" value="Submit" />
</form>
<h2>Business Transaction</h2>
<form action="/Transaction/Business" method="post">
<label for="BusinessName">Business Name:</label>
<input type="text" id="BusinessName" name="BusinessName" />
<label for="ReferenceNumber">Reference Number:</label>
<input type="text" id="ReferenceNumber" name="ReferenceNumber" />
<input type="submit" value="Submit" />
</form>
Since ReferenceNumber is in both models, I'm getting a duplicate id on the page. I figured out that i can pass an extra htmlAttributes parameter to TextBoxFor to change the id.
@Html.TextBoxFor(m => m.ReferenceNumber, new { id = "ResidentialReferenceNumber" })
...
@Html.TextBoxFor(m => m.ReferenceNumber, new { id = "BusinessReferenceNumber" })
This fixes the ids on the inputs but the 'for' attribute on the labels still has the wrong value. I looked through the various overloads for LabelFor() and unlike the TextBoxFor, there isn't an htmlAttributes property. Is there some way that I can tell model or view to use a different id for these fields?
MVC helpers do not take into account that you can have multiple models in a view. All properties that have the same name will get duplicate values (one value per model).
That is, if ResidentalTransaction and BusinessModel has a Name
property, your html form will have two <input type="text" name="Name" />
fields.
I'm unsure of how it works if you add all models to the same viewmodel and use Html.TextBoxFor(m => m.ResidentalTransaction.Id);
精彩评论