开发者

Is there an MVC Helper Method that can be used to get the name of a form element?

With ASP.net MVC I have a Model like so:

public class Project {
    public string ProjectName { get; set; }
    // SNIP ...
}

My View contains:

@model Project

@Html.TextBoxFor(m => m.ProjectName)

I would like to write some javascript that references the textbox:

<script type="tex开发者_Go百科t/javascript">
    $('#ProjectName').someMethod();
</script>

I don't want to hard code ProjectName in there. Ideally, I would like to use a helper method to get what the name is, just in case I refactor and rename the property:

<script type="text/javascript">
    $('#@Html.NameFor(m => m.ProjectName)').someMethod();
</script>

Is there something like this that I can use? I don't want to use a CSS class to trigger this, because I want to put this in an Editor Template and I don't want the code to execute for every instance of the class for every text box. I want it to execute for the one element.


There are Html.NameFor / Html.IdFor helpers in the ASP.NET MVC Futures assembly (Microsoft.Web.Mvc) which you can pull through NuGet and work exactly like that using lambda/expressions instead of literal string property name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜