mvc3 html.displayfor-可以使此控件生成一个ID



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

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

如果我使用Editor而不是Display For,我会看到输入控件的ID。不过,我不希望该价值以这种方式进行编辑。因此,我将其作为显示为显示,但是它不会为该元素生成ID属性。

我应该只将显示器包裹在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>

避免'魔术字符串'输入(如果您的模型属性更改),您可以使用扩展名来执行此操作。它还制作了更干净的代码:

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>

non-razor

对于非剃刀语法,您只需这样使用:

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

和:

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

您必须使用:

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

在您的模型中,您可以使用affshtml as:

[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属性自动

只需在列上方添加一个隐藏的。这将为您提供一个ID,以适合您的需求。简单,为您提供了通过ID获取该值的功能。

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

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');

我们不能在剃须刀中为displayfor()控制创建ID ..我们可以使用html控件,例如跨度的标签,而不是displayfor()控制。其他明智的选择,我们可以将Display For Control放在SPAN控件中。现在我们可以为跨度创建ID。这是我们必须做的。

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

以下是添加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)));
        }
    }

对我来说最简单的解决方案是使用一个可读的文本框。@html.textboxfor(u => u.visibilidade,new {disabled =" disabled"})

相关内容

  • 没有找到相关文章