tags:

views:

10

answers:

1

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.

A: 

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(

Jesper Palm
Thanks. I was hoping there was a way to set the ID of the text input element, but I'll go with this. And yes, you're right, though I get the same output whatever I set the lambda expression to.
Matt W