MVC3 Html.DisplayFor - 是否可以让此控件生成ID?

时间:2012-10-18 17:47:41

标签: jquery asp.net-mvc asp.net-mvc-3

我希望能够显示一些文本,但也可以通过jQuery修改文本。

<%= Html.DisplayFor(model => model.DeviceComponentName)%>

如果我使用EditorFor而不是DisplayFor,我会看到输入控件的ID。不过,我不希望以这种方式编辑值。所以,我把它变成了DisplayFor,但它没有为元素生成ID属性。

我应该将DisplayFor包装在div中并执行以下操作:

<div id="<%= ViewData.TemplateInfo.GetFullHtmlFieldName("DeviceComponentName") %>">
    <%= Html.DisplayFor(model => model.DeviceComponentName)%>
</div>

$('#DeviceComponentName').text('newValue');

或者是否有更清洁的方法来实现这一目标?

更新:有没有一种方法不依赖于硬编码字符串?与对象本身有关系的东西,所以如果我的属性名称发生变化,我会收到编译错误吗?

此外,我正在使用此代码,但我没有看到ID值:

<td class="editableValue">
    <%--Label should be editable, so it needs an ID, but only will be edited by jQuery so it can't be an EditorFor--%>
    <%= Html.DisplayFor(model => model.DeviceComponentName, new { id = "DeviceComponentName" })%>
    <button type="button" id="ComponentTreeButton" class="nestedDialogButton">...</button>
</td>

7 个答案:

答案 0 :(得分:18)

要避免“魔术字符串”输入(如果您的模型属性发生更改),您可以使用扩展名执行此操作。它还使代码更清晰:

public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "div")
{
    var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
    return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}</{0}>", wrapperTag, id, helper.DisplayFor(expression)));
}

然后简单地使用它:

@Html.DisplayWithIdFor(x => x.Name)

将产生

<div id="Name">Bill</div>

或者如果你想把它包裹在一个范围内:

@Html.DisplayWithIdFor(x => x.Name, "span")

将会:

<span id="Name">Bill</span>

<强>非剃刀

对于非R​​azor语法,您只需使用它:

<%= Html.DisplayWithIdFor(x => x.Name) %>

<%= Html.DisplayWithIdFor(x => x.Name, "span") %>

答案 1 :(得分:5)

你必须使用:

Html.DisplayFor(model => model.DeviceComponentName, new { @id = "DeviceComponentName"})

对于动态ID和其他属性,我使用:

元数据类:

public class AdditionalHtml : Attribute, IMetadataAware
{
    public string Id { get; set; }

    public string Type { get; set; }

    public string CssClass { get; set; }

    public string PlaceHolder { get; set; }

    public string Style { get; set; }

    public string OnChange { get; set; }

    public int Rows { get; set; }

    public int MaxLength { get; set; }

    public bool ReadOnly { get; set; }

    public bool Disabled { get; set; }

    public Dictionary<string, object> OptionalAttributes ()
    {
        var options = new Dictionary<string, object>();

        if ( !string.IsNullOrWhiteSpace( Id ) )
            options.Add( "id", Id );

        if ( !string.IsNullOrWhiteSpace( Type ) )
            options.Add( "type", Type );

        if ( !string.IsNullOrWhiteSpace( CssClass ) )
            options.Add( "class", CssClass );

        if ( !string.IsNullOrWhiteSpace( PlaceHolder ) )
            options.Add( "placeholder", PlaceHolder );

        if ( !string.IsNullOrWhiteSpace( OnChange ) )
            options.Add( "onchange", OnChange );

        if ( !string.IsNullOrWhiteSpace( Style ) )
            options.Add( "style", Style );

        if ( Rows != 0 )
            options.Add( "rows", Rows );

        if ( MaxLength != 0 )
            options.Add( "maxlength", MaxLength );

        if ( ReadOnly )
            options.Add( "readonly", "readonly" );

        if ( Disabled )
            options.Add( "disabled", "disabled" );

        return options;
    }

元数据提供者类:

public class MetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata ( IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName )
    {
        var metadata = base.CreateMetadata( attributes, containerType, modelAccessor, modelType, propertyName );

        var additionalHtmlValues = attributes.OfType<AdditionalHtml>().FirstOrDefault();

        if ( additionalHtmlValues != null )
        {
            metadata.AdditionalValues.Add( "AdditionalHtml", additionalHtmlValues );
        }

        return metadata;
    }
}

添加助手:

public static class HtmlAttributesHelper
{
    public static string GetHtmlAttribute<T> ( this T model, Expression<Func<T, object>> expression, string attribName )
    {
        string strDefault = String.Empty;
        MemberInfo member = null;

        switch ( expression.Body.NodeType )
        {
            case ExpressionType.Lambda:
            case ExpressionType.Convert:
                {
                    var body = expression.Body as UnaryExpression;
                    if ( body == null )
                        return strDefault;
                    var operand = body.Operand as MemberExpression;
                    if ( operand == null )
                        return strDefault;
                    member = operand.Member;
                    break;
                }
            case ExpressionType.MemberAccess:
                {
                    var body = expression.Body as MemberExpression;
                    if ( body == null )
                        return strDefault;
                    member = body.Member;
                    break;
                }
            default:
                {
                    return expression.Body.ToString() + " " + expression.Body.NodeType.ToString();
                }
        }

        if ( member == null )
            return strDefault;

        var attr = member.GetCustomAttributes( typeof( AdditionalHtml ), false );
        if ( attr.Length > 0 )
        {
            return ( attr [ 0 ] as AdditionalHtml ).OptionalAttributes() [ attribName.ToLower() ].ToString();
        }

        // Return Name of Property if AdditionalHtml.Id is empty
        return attribName == "Id" ? member.Name : strDefault;
    }

    public static string GetHtmlId<T> ( this T model, Expression<Func<T, object>> expression )
    {
        return model.GetHtmlAttribute( expression, "Id" );
    }
}

在Global.asax中注册提供程序:

protected void Application_Start ()
    {
        AreaRegistration.RegisterAllAreas();

        //....
        ModelMetadataProviders.Current = new MetadataProvider();
    }

在你的模型中你可以使用AdditionHtml,如:

[AdditionalHtml( Id = "OrderNo", CssClass = ShortTextStyle, Disabled = true )]
    public string OrderNo { get; set; }

现在你可以将sintax用于js(在视图中):

$('#@Model.GetHtmlId( x => x.PropertyName)')

在视图中,您可以使用:

@Html.DisplayFor( x => x.FormDate )

自动附加Html属性

答案 2 :(得分:3)

只需在列上方添加HiddenFor即可。这将为您提供用于所需内容的ID。很简单,你可以通过ID获取该值。

<%= Html.HiddenFor(model => model.DeviceComponentName)%>
<%= Html.DisplayFor(model => model.DeviceComponentName)%>

答案 3 :(得分:2)

HtmlHelpers具有覆盖,允许您传入对象或字典,以将属性添加到生成的html标记中:

@Html.DisplayFor(model => model.DeviceComponentName, new { id = "myId" })

@Html.DisplayFor(model => model.DeviceComponentName, new Dictionary<string, object>() { { "id", "myId" } })

@Html.DisplayFor(model => model.DeviceComponentName, new { id = ViewData.TemplateInfo.GetFullHtmlFieldName("DeviceComponentName") })

@Html.DisplayFor(model => model.DeviceComponentName, new Dictionary<string, object>() { { "id", ViewData.TemplateInfo.GetFullHtmlFieldName("DeviceComponentName" } })

<强>更新

在查看更新的代码并重新阅读问题后,我会建议这一点 - 这与您的第一个想法类似。

<td class="editableValue" id="<%= ViewData.TemplateInfo.GetFullHtmlFieldName("DeviceComponentName") %>">
  <%= Html.DisplayFor(model => model.DeviceComponentName)%>
  <button type="button" id="ComponentTreeButton" class="nestedDialogButton">...</button>
</td>

您不需要在TD中添加额外的div,因为您可以通过jQuery直接修改td中的值。我相信以下内容应该做到这一点:

$('#DeviceComponentName').html('newValue');

答案 4 :(得分:1)

我们无法在razor中为Displayfor()控件创建id。我们可以使用html控件,如span的标签而不是Displayfor()控件。其他明智的我们可以将显示控制放在跨度控制中。现在我们可以为span创建id。这就是我们必须做的事情..

示例<span id="spanid">@Html.Displayfor(modelItem => item.id) </span>

答案 5 :(得分:0)

这是一个能够添加htmlAttributes的naspinski解决方案。

    public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes, string wrapperTag = "div")
    {
        var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));

        if (htmlAttributes != null)
        {
            var tag = new TagBuilder(wrapperTag);
            tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) as IDictionary<string, object>);
            tag.Attributes.Add("id", id);
            tag.SetInnerText(helper.DisplayFor(expression).ToHtmlString());

            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
        else
        {
            return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}</{0}>", wrapperTag, id, helper.DisplayFor(expression)));
        }
    }

答案 6 :(得分:0)

对我来说最简单的解决方案是使用只读文本框。 @ Html.TextBoxFor(u =&gt; u.Visibilidade,new {disabled =&#34; disabled&#34;})