Jamie Kitson
Jamie Kitson

Reputation: 4140

C# MVC property name to HTML id

I know that I could do this manually, but is there a built in function to convert a C# MVC Razor property name to the value that Razor will use as the HTML id?

To expand on this question:

I am trying to access the HTML element using JavaScript in a partial view. (The partial view means that I do not have access to the parameter name directly.)

The following two partial solutions double up the ID, giving you ParameterName_ParameterName:

string name = ViewData.TemplateInfo.HtmlFieldPrefix
@Html.Id(name)
@ViewData.TemplateInfo.GetFullHtmlFieldId(name)

The solution I'm going with at the moment:

Regex.Replace(name, @"[\.\[\]]", "_");

I guess you could add parentheses.

Upvotes: 2

Views: 2735

Answers (2)

Inari
Inari

Reputation: 554

As per your comments:

IMHO you should not be using your model in that fashion. If you need access to children objects, create a new model and bind to it that exposes that directly. Then in your controller piece back together your original model as needed. In the case of a Registration Form, if its highly complex, try breaking it up in to smaller pieces (seperate views), otherwise use a flat model that combines all the fields like Username, Password, etc then assign values to the appropriate objects.

Remember that the least amount of complexity is the better solution, as it improves maintainability.

Upvotes: 1

When you define a moldel

something like this

 public class AnnonymousModel
    {
        [Required]
        [StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
        [Display(Name = "User name")]
        [RegularExpression(@"^[A-Za-z\n\r\0-9_ ]+$")]
        public String RegisterUsername {get; set;}
   }

and then use it in mvc view page

For Razor

@Html.TextBoxFor(m => m.RegisterUsername, new { @class = "inp-form", @placeholder = "User name" })

For asp

<%Html.TextBoxFor(m => m.RegisterUsername, new { @class = "inp-form", @placeholder = "User name" })%>

the in the Html renderd is like this

<input type="text" value="" placeholder="User name" name="RegisterUsername" 
id="RegisterUsername" data-val-required="The User name field is required." data-val-regex-

pattern="^[A-Za-z\n\r\0-9_ ]+$" data-val-regex="The field User name must match the regular 

expression '^[A-Za-z\n\r\0-9_ ]+$'." data-val-length-min="3" data-val-length-max="20" 

data-val-length="The User name must be at least 3 characters long." data-val="true" 

class="inp-form">

So the Id is automatically generated as the property name specified.

Upvotes: 0

Related Questions