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

Sea*_*son 9 asp.net-mvc jquery asp.net-mvc-3

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

<%= Html.DisplayFor(model => model.DeviceComponentName)%>
Run Code Online (Sandbox Code Playgroud)

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

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

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

$('#DeviceComponentName').text('newValue');
Run Code Online (Sandbox Code Playgroud)

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

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

此外,我使用此代码,但我没有看到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>
Run Code Online (Sandbox Code Playgroud)

nas*_*ski 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)));
}
Run Code Online (Sandbox Code Playgroud)

然后简单地使用它:

@Html.DisplayWithIdFor(x => x.Name)
Run Code Online (Sandbox Code Playgroud)

会生产

<div id="Name">Bill</div>
Run Code Online (Sandbox Code Playgroud)

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

@Html.DisplayWithIdFor(x => x.Name, "span")
Run Code Online (Sandbox Code Playgroud)

这将使:

<span id="Name">Bill</span>
Run Code Online (Sandbox Code Playgroud)

非剃刀

对于非Razor语法,您只需使用它:

<%= Html.DisplayWithIdFor(x => x.Name) %>
Run Code Online (Sandbox Code Playgroud)

和:

<%= Html.DisplayWithIdFor(x => x.Name, "span") %>
Run Code Online (Sandbox Code Playgroud)

  • 非剃刀语法是否应该在Html之前使用@? (2认同)

Xor*_*dal 5

你必须使用:

Html.DisplayFor(model => model.DeviceComponentName, new { @id = "DeviceComponentName"})
Run Code Online (Sandbox Code Playgroud)

对于动态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;
    }
Run Code Online (Sandbox Code Playgroud)

元数据提供者类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

添加助手:

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" );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

        //....
        ModelMetadataProviders.Current = new MetadataProvider();
    }
Run Code Online (Sandbox Code Playgroud)

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

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

现在你可以使用sintax作为js(在视图中):

$('#@Model.GetHtmlId( x => x.PropertyName)')
Run Code Online (Sandbox Code Playgroud)

在视图中,您可以使用:

@Html.DisplayFor( x => x.FormDate )
Run Code Online (Sandbox Code Playgroud)

自动附加Html属性

  • @SeanAnderson是的,您可以使用ViewBag或ViewData从控制器传递id值@ Html.DisplayFor(model => model.DeviceComponentName,new {id = ViewBag.DeviceComponentID})` (2认同)