属性的客户端 ID (ASP.Net MVC) [英] Client Id for Property (ASP.Net MVC)

查看:30
本文介绍了属性的客户端 ID (ASP.Net MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的视图中的 TextBox 做一个标签,我想知道,我如何获取将在客户端呈现的 ID 以生成脚本...例如:

I'm trying to do a label for a TextBox in my View and I'd like to know, how can I take a Id that will be render in client to generate scripts... for example:

<label for="<%=x.Name.ClientId%>"> Name: </label>
<%=Html.TextBoxFor(x=>x.Name) %>

我需要在ClientId"中输入什么才能确保将正确的Id呈现给相应的控件?

What do I need to put in "ClientId" to make sure that the correct Id will be rendered to the corresponding control?

推荐答案

将此代码放在某处:

using System; 
using System.Linq.Expressions; 
using System.Web.Mvc; 

namespace MvcLibrary.Extensions 
{ 
    public static class HtmlExtensions 
    { 
        public static MvcHtmlString FieldIdFor<TModel, TValue>(this HtmlHelper<TModel> html,
            Expression<Func<TModel, TValue>> expression) 
        { 
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
            string inputFieldId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName); 
            return MvcHtmlString.Create(inputFieldId); 
        } 
    } 
}

然后在您的 ASPX 视图中:

Then in your ASPX view:

<label for="<%= Html.FieldIdFor(m => m.EmailAddress) %>">E-mail address:</label> 
<%= Html.TextBoxFor(m => m.EmailAddress) %>

您也可以在 JavaScript 调用中使用它,因为您不会事先知道控件的 ID,并且可能需要它来让某些 JavaScript 代码对其进行处理:

You can also use this in JavaScript calls as you won't know the control's ID in advance and may need it for some JavaScript code to work against it:

<script> $.CoolJQueryFunction('<%= Html.FieldIdFor(m => m.EmailAddress) %>'); </script>

这里有人提到的 LabelFor HTML helper 方法不会让您指定要使用的实际文本标签,您必须使用属性来装饰您的 ViewModel 以设置标签文本,恕我直言很难看.我宁愿这些东西出现在实际的 ASPX 视图部分本身中,而不是出现在某些域/视图模型中.不过有些人会不同意我的看法.

The LabelFor HTML helper method, that someone mentioned here, won't let you specify the actual text label you want to use, you have to decorate your ViewModels with attributes to set the label text, with IMHO is ugly. I'd rather that stuff appear in the actual ASPX view part itself, not on some domain/view model. Some people will disagree with me though.

不确定发布博客文章链接的规则,但我发布了一篇关于这个确切主题的博客:http://www.dominicpettifer.co.uk/Blog/37/strongly-typed--label--elements-in-asp-net-mvc-2

Not sure of the rules for posting links to one's blog posts, but I posted a blog on this exact topic: http://www.dominicpettifer.co.uk/Blog/37/strongly-typed--label--elements-in-asp-net-mvc-2

这篇关于属性的客户端 ID (ASP.Net MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆