繁体   English   中英

Asp.net MVC动态Html属性

[英]Asp.net MVC dynamic Html attributes

我的视图文本框,下拉列表等中的元素很少。所有元素都有一些像这样创建的独特属性

<%: Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList< MyType >(),new { @class = "someclass", @someattrt = "someattrt"})%>

我想通过设置另一个属性禁用来创建我的页面的只读版本。

有人知道我怎么能使用可以全局设置的变量来做到这一点?

就像是:

If(pageReadOnly){
isReadOnlyAttr  = @disabled = "disabled";
}else 
{
isReadOnlyAttr   =”” 
} 

<%: Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList< MyType >(),new { @class = "someclass", @someattrt = "someattrt",isReadOnlyAttr})%>

我不想使用JavaScript来做到这一点

在我想到之后,我做了类似于你的事情 - 基本上我有几个不同的系统用户,一套在网站上拥有只读权限。 为了做到这一点,我在每个视图模型上都有一个变量:

public bool Readonly { get; set; }

根据其角色权限在我的模型/业务逻辑层中设置。

然后我创建了DropDownListFor Html Helper的扩展,它接受一个布尔值,指示下拉列表是否应该只读:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class DropDownListForHelper
{
    public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> dropdownItems, bool disabled)
    {
        object htmlAttributes = null;

        if(disabled)
        {
            htmlAttributes = new {@disabled = "true"};
        }

        return htmlHelper.DropDownListFor<TModel, TProperty>(expression, dropdownItems, htmlAttributes);
    }
}

请注意,您还可以创建其他具有更多参数的实例。

在我的视图中,我只是为我的html帮助扩展导入了命名空间,然后将视图模型变量readonly传递给DropDownListFor Html帮助器:

<%@ Import Namespace="MvcApplication1.Helpers.HtmlHelpers" %>

<%= Html.DropDownListFor(model => model.MyDropDown, Model.MyDropDownSelectList, Model.Readonly)%>

我为TextBoxFor,TextAreaFor和CheckBoxFor做了同样的事情,它们似乎都运行良好。 希望这可以帮助。

而不是禁用下拉列表,为什么不用选定的选项替换它......如果你为很多东西做这个,你应该考虑有一个只读视图和一个可编辑的视图......

<% if (Model.IsReadOnly) { %>
    <%= Model.MyModel.MyType %>
<% } else { %>
    <%= Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList< MyType >(),new { @class = "someclass", someattrt = "someattrt"})%>
<% } %>

另外,如果它是一个保留字,例如“class”,你只需要用“@”来转义属性名称。

更新

好的。 我确实有一个答案 - 但条件是你在实施它之前阅读这些东西。

MVC就是将关注点分开。 将逻辑放在特别关注视图的控制器中是滥用MVC。 请不要这样做。 任何特定于视图的东西,比如HTML,属性,布局 - “控制器维护”中都没有这个特征。 控制器不应该更改,因为您想要在视图中更改某些内容。

了解MVC正在尝试实现的内容以及以下示例打破整个模式并将视图内容放在应用程序中的错误位置非常重要。

正确的解决方法是拥有“读取”视图和“编辑”视图 - 或者在视图中放置任何条件逻辑。 但这是一种做你想做的事情的方法。 :(

将此属性添加到模型。

public IDictionary<string, object> Attributes { get; set; }

在控制器中,您可以有条件地设置属性:

model.Attributes = new Dictionary<string, object>();
model.Attributes.Add(@"class", "test");
if (isDisabled) {
    model.Attributes.Add("disabled", "true");
}

使用视图中的属性:

<%= Html.TextBoxFor(model => model.SomeValue, Model.Attributes)%>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM