How to name textboxes in MVC when passing XElement
-
25-09-2019 - |
Question
I'm passing an XElement to my Edit view and want to have the usual HTML controls built for me and correctly named. The code I have is:
...
<div class="editor-label">
<%= Html.LabelFor(model => Model.XPathSelectElement("site[@id = 'customerName']").Value)%>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => Model.XPathSelectElement("site[@id = 'customerName']").Value)%>
<%= Html.ValidationMessageFor(model => Model.XPathSelectElement("site[@id = 'customerName']").Value)%>
</div>
...
But this produces the following:
<div class="editor-label">
<label for="Value">Value</label>
</div>
<div class="editor-field">
<input id="Value" name="Value" type="text" value="" />
</div>
Why is this and how do I get the view to generate sensibly-named (eg) TextBoxes?
Thanks,
Matt.
Solution
You should really create a ViewModel to hold your view data instead of passing it the full xml element.
For example:
public class CustomerModel
{
public CustomerModel(XElement xml)
{
this.Name = xml.XPathSelectElement("site[@id = 'customerName']").Value;
}
public string Name { get; set; }
}
And then simply: Html.TextBoxFor(model => model.Name);
Edit: And also... Shouldn't your <%= Html.LabelFor(model => Model.XPathSelectElement( be %= Html.LabelFor(model => model.XPathSelectElement(
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow