c# - ASP.NET MVC : 'Extend' Html. TextBox 有条件地具有 CSS 值?

标签 c# asp.net asp.net-mvc extension-methods html-helper

我想扩展 ASP.NET MVC 的 TextBox,以便它有条件地切换其 CSS 值(基于来自模型的数据)。但是,我不想将该逻辑放在我的 View 中(通过有条件地更改 htmlAttributes/通过那里的方法调用),而是扩展类,这样我就不会弄乱我的 View 。基本上我希望 TextBox 在创建时查看模型,看看它是否有一个带有自己名称的字典条目,然后在找到它时查找关联的 CSS 值。

我遇到的问题是:

1) 如何扩展它? TextBox 本身已经是一个扩展方法而不是一个类,所以我不能“继承”?

2) 我如何将影响 TextBox 属性的条件从我的 Controller 方法传达给 TextBox?

最佳答案

您可能不应该将文本框耦合回模型。始终以一种方式拥有依赖关系是更好的主意。从模型到 View 。

所以间接的答案是有另一种扩展方法,它将接受枚举或 bool 值,并根据它添加或不添加类名。

<%= Html.StyledTextBox("myField", ViewData["ShouldBeStyled"]) %>

也有直接的回答。

要扩展 ASP.NET MVC,您应该编写自己的扩展方法。您始终可以调用下划线扩展方法。所以你的代码看起来像:

public static class MyCoolExtension
{
  public static string TextBox(this HtmlHelper htmlHelper, string name)
  {
     // get data from htmlHelper.ViewData and call another extension methods of the HtmlHelper 
    var className = htmlHelper.ViewData["someClass"];
    return htmlHelper.TextBox("myField", "30", new { @class = className });
  }
}

关于c# - ASP.NET MVC : 'Extend' Html. TextBox 有条件地具有 CSS 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1292240/

相关文章:

c# - LongListSelector 停止滚动并卡住

asp.net - CustomValidator 在客户端上触发,但验证失败时验证控件不会呈现

javascript - 自动将版本添加到 asp.net header runat ="server"内的 js 文件

javascript - 正在验证 MVC 隐藏字段

c# - ViewModel 返回默认值 0

c# - 扩展 Outlook 2010 中的用户界面以添加到右键单击菜单

c# - 您如何在 .Net 项目中使用 'lib' 文件夹来构建依赖项?

c# - Cake 脚本 Alias/Addin 的最基本示例是什么?

asp.net - 我如何知道新生成的密码

asp.net-mvc - 设计决策 - 扩展基于 Web 的应用程序架构