1

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.

4

2 回答 2

1

根据您的评论:

恕我直言,您不应该以这种方式使用您的模型。如果您需要访问子对象,请创建一个新模型并绑定到它直接公开它。然后在您的控制器中根据需要将原始模型重新组合在一起。在注册表的情况下,如果它非常复杂,请尝试将其分解为更小的部分(单独的视图),否则使用一个平面模型,该模型将所有字段(如用户名、密码等)组合在一起,然后将值分配给适当的对象。

请记住,最少的复杂性是更好的解决方案,因为它提高了可维护性。

于 2013-10-16T15:33:48.880 回答
0

定义模型时

像这样的东西

 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;}
   }

然后在 mvc 视图页面中使用它

剃须刀

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

对于 asp

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

呈现的Html中是这样的

<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">

所以Id就像. automatically generated_property name specified

于 2013-10-16T11:37:47.067 回答