views:

36

answers:

2

Given the following MVC mark-up:

    <p>
        <label for="forenamesLabel">Forename(s):</label>
        <%: Html.TextBoxFor(model => model.ConsultantRegistrationDTO.Forenames) %>
        <%: Html.ValidationMessageFor(model => model.ConsultantRegistrationDTO.Forenames, "*") %>
    </p>

How is it possible for me to accurately set the label/@for attribute to the id of the generated TextBox by MVC? If I use @id as an HTML option, wouldn't that break my binding?

+1  A: 

You can use

Html.LabelFor(c model => model.ConsultantRegistrationDTO.Forenames)

Then in your model you need to specify the DisplayNameAttribute from System.ComponentModel.DataAnnotations. So your model would look something like this:

public class ConsultantModel
{
    [DisplayName("Forenames")]
    public string Forenames { get; set; }
}
Keltex
Thanks, that has got it. Only problem is, my model is a generated class from WCF so can't add an attribute. Am I wrong to use my model as a WCF DataContract class or is there an alternative way? (Sorry, new to MVC)
Program.X
+1  A: 

As was suggested by Keltex you can use Html.LabelFor with a DisplayName decorator. A few considerations that go along with this.

LabelFor and DisplayName decorators are specific to MVC 2. This may or may not be an option for you.

Using this method, specifically using the DisplayName decorator, introduces View concerns into your Model which is sometimes not desirable. It is usually better to create a ViewModel and use the decorator there to preserve separation of concerns.

This also allows you to use the DisplayNameAttribute when your model is auto-generated as you've said yours is.

mwright
MVC 2 is fine. Project is due post-April 12th so should be fine. Thanks very much. I will have a look at what you said. You're right in the concerns issue. I am actually already using a ViewModel, which has a property which is my DTO object from WCF. I'll play with what you suggest, in conjunction with buddy classes. http://davidhayden.com/blog/dave/archive/2009/08/10/AspNetMvc20BuddyClassesMetadataType.aspx
Program.X