有条件禁用Html.DropDownList [英] Conditionally disable Html.DropDownList

查看:195
本文介绍了有条件禁用Html.DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能改变这种DropDownList的声明,使残疾人属性启用/禁用条件?

 <%= Html.DropDownList(数量,新的SelectList(...),新的{@禁用=禁用}%GT;

非工作的例子:

<?pre> &LT;%= Html.DropDownList(数量,新的SelectList(...),new{@disabled=Model.CanEdit假:已禁用}% &GT;

P.S。增加一个条件,如果围绕整个语句不是期望的做法:)

编辑:根据<一个href=\"http://stackoverflow.com/questions/233711/add-property-to-anonymous-type-after-creation/4416536#4416536\">this从另一个问题扩展方法,我想出了以下扩展:

 公共静态的IDictionary&LT;字符串对象&gt;残疾人(这obj对象,布尔禁用)
{
  返回禁用? obj.AddProperty(禁用,已禁用):obj.ToDictionary();
}

然后可以用作

 &LT;%= Html.DropDownList(数量,新的SelectList(...),新{ID =量}禁用(Model.CanEdit)%GT;


解决方案

请不要写面条code。 HTML辅助在那里为这个目的:

 公共静态MvcHtmlString DropDownList的(这个HTML的HtmlHelper,字符串名称,值的SelectList,布尔canEdit)
{
    如果(canEdit)
    {
        返回html.DropDownList(名称,值);
    }
    返回html.DropDownList(名称,价值,新的{禁用=禁用});
}

和则:

 &LT;%= Html.DropDownList(数量,新的SelectList(...),Model.CanEdit)%GT;

或者,也许你能想出一些更好(如果模型中包含的选项):

 &LT;%= Html.DropDownList(数量,模型)%GT;

您也将获得有更多的单元测试code的奖金。

How can I change this DropDownList declaration so that the disabled attribute is enable/disabled conditionally?

<%= Html.DropDownList("Quantity", new SelectList(...), new{@disabled="disabled"} %>

non-working example:

<%= Html.DropDownList("Quantity", new SelectList(...), new{@disabled=Model.CanEdit?"false":"disabled"} %>

p.s. adding an if condition around the entire statement is not a desired approach :)

EDIT: based on this extension method from another question I came up with the following extension:

public static IDictionary<string, object> Disabled (this object obj, bool disabled)
{
  return disabled ? obj.AddProperty ("disabled", "disabled") : obj.ToDictionary ();
}

which can then be used as

<%= Html.DropDownList("Quantity", new SelectList(...), new{id="quantity"}.Disabled(Model.CanEdit) %>

解决方案

Please don't write spaghetti code. Html helpers are there for this purpose:

public static MvcHtmlString DropDownList(this HtmlHelper html, string name, SelectList values, bool canEdit)
{
    if (canEdit)
    {
        return html.DropDownList(name, values);
    }
    return html.DropDownList(name, values, new { disabled = "disabled" });
}

And then:

<%= Html.DropDownList("Quantity", new SelectList(...), Model.CanEdit) %>

Or maybe you could come up with something even better (if the model contains the options):

<%= Html.DropDownList("Quantity", Model) %>

You will also get the bonus of having more unit testable code.

这篇关于有条件禁用Html.DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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