【问题标题】:How do I add HtmlAttributes in mvc using ViewBag or Model values?如何使用 ViewBag 或 Model 值在 mvc 中添加 HtmlAttributes?
【发布时间】:2012-06-22 20:05:12
【问题描述】:

我有一个文本区域,我可能想在某些情况下禁用它。我想将此信息作为 ViewBag 参数发送,但我不知道该怎么做。

我认为的textarea是这样的

@Html.TextAreaFor(f => f.ProgressDetail, new { @class = "followUpProgress", ViewBag.DisableProgressDetail })

在控制器中我有这样的东西:

if(conditions)
    ViewBag.DisableProgressDetail = "disabled=\"disabled\"";

然而,html 输出是这样的:

<textarea DisableProgressDetail="disabled=&quot;disabled&quot;" class="followUpProgress" cols="20" id="ProgressDetail" name="ProgressDetail" rows="2">
</textarea>

【问题讨论】:

    标签: asp.net-mvc razor viewbag


    【解决方案1】:

    你想要的是这个:

    @Html.TextAreaFor(f => f.ProgressDetail, new { @class = "followUpProgress", disabled = ViewBag.DisableProgressDetail })
    

    然后在你的控制器中,做它:

    ViewBage.DisableProgressDetail = "disabled";
    

    【讨论】:

    • 当我看到一个新的答案已经到来时,我实际上正要发布它作为我自己的答案。 :)
    【解决方案2】:

    如果未指定属性,则该属性来自属性名称,这就是为什么您会获得一个为 ViewBag 属性命名的 html 属性。使其工作的一种方法是:

    // in the view:
    @Html.TextAreaFor(f => f.ProgressDetail, new { @class = "followUpProgress", ViewBag.disabled })
    -------------------------------------------------------------
    // in the controller
    ViewBag.disabled = "disabled";
    

    如果您不喜欢这种方法,您可以像这样设置禁用位:

    // in the view:
    @Html.TextAreaFor(f => f.ProgressDetail, new { @class = "followUpProgress", disabled=ViewBag.DisableProgressDetail })
    -------------------------------------------------------------
    // in the controller:
    if(conditions)
        ViewBag.DisableProgressDetail = "disabled";
    else
        ViewBag.DisableProgressDetail = "false";
    
    // or more simply
    ViewBag.DisableProgressDetail = (conditions) ? "disabled" : "false";
    

    【讨论】:

      【解决方案3】:

      它不起作用。你可以试试这个:

      //In the controller
      
      if(Mycondition){ ViewBag.disabled = true;}
      else { ViewBag.disabled = false;}
      
      //In the view
      
      @Html.TextBoxFor(model => model.MyProperty, ViewBag.disabled ? (object)new { @class = "MyClass", size = "20", maxlength = "20", disabled = "disabled" } : (object)new { @class = "MyClass", size = "20", maxlength = "20" })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-27
        • 1970-01-01
        • 2011-02-18
        • 2020-12-22
        相关资源
        最近更新 更多