Gumowy Kaczak
Gumowy Kaczak

Reputation: 1499

MVC3 - DataAnnotation - propertys name

I do a lot of coding in jQuery for my project, but I need help with obtaining parameter names genereated by Helper with For suffix.

When I do:

Html.TextBoxFor(model => model.SomeTextParameter)  

in pure html there's generated id: "SomeTextParameter". I'd like to get its id automagically generated in every place I use it in jQuery. How to do that?

Or, I can always manualy specify it's name by using helper without "For":

Html.TextBox("SomeTextParameter", this.Model.SomeTextParameter)

In this case I can control ids with easy but when I want to use Data Annotations for labels then I find another problem with connecting [Display(Name = "Really important text parameter")] with Html.Label("SomeTextParameterLabel", <what to enter here?>).

When I use:

Html.LabelFor(model => model.SomeTextParameter)

it binds to display name so it's displayed just as I want.

Any ideas how to solve 1st or 2nd problem?

Upvotes: 0

Views: 420

Answers (2)

Yasir Mughal
Yasir Mughal

Reputation: 83

public class LogOnModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

<ol>
    <li>
        @Html.LabelFor(m => m.UserName)
        @Html.TextBoxFor(m => m.UserName)
        @Html.ValidationMessageFor(m => m.UserName)
    </li>
    <li>
        @Html.LabelFor(m => m.Password)
        @Html.PasswordFor(m => m.Password)
        @Html.ValidationMessageFor(m => m.Password)
    </li>
    <li>
        @Html.CheckBoxFor(m => m.RememberMe)
        @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
    </li>
</ol>

Upvotes: 1

krolik
krolik

Reputation: 5802

You can write your own helper to get generated ids. This should be useful https://stackoverflow.com/a/5419261/472126

After that, you should be able to get generated Id by using this

<%: Html.ClientIdFor(model => model.SomeTextParameter) %>

Upvotes: 0

Related Questions