我想实现类似于@Html.TextBoxFor 的东西,而是调用@Html.SwitchFor() 从我正在使用的布尔创建一个是/否开关,而不必每次都添加额外的html和类。
有没有办法用剃刀语法做到这一点?
我想实现类似于@Html.TextBoxFor 的东西,而是调用@Html.SwitchFor() 从我正在使用的布尔创建一个是/否开关,而不必每次都添加额外的html和类。
有没有办法用剃刀语法做到这一点?
你可能会很幸运。
请注意,您应该发现自己将鼠标悬停在TextBoxFor 上并在Visual Studio中单击F12,您将获得您尝试模仿的方法的签名。这是一个很好的起点,虽然如果你不花时间阅读会有点困难。
public static MvcHtmlString SwitchFor<TModel>(
this HtmlHelper<TModel> helper, Expression<Func<TModel,
Object>> expression, Boolean wrap)
{
return wrap
? MvcHtmlString.Create(String.Format("<div class='helloworld'>{0}</div>",
helper.TextAreaFor(expression))) : helper.TextAreaFor(expression);
}
传递正确的东西
您需要将表达式传递给TextBoxFor扩展。m =>的方法签名是Func,它将您的TModel (m) 传递给函数并返回一个对象。
做你想做的事并返回默认实现
你可以在里面放任何东西。您可以看到,如果wrap设置为 false,我只是返回传递表达式的原始方法调用。
拨打电话
剩下要做的就是按照您最初的意图拨打电话。
@(Html.SwitchFor(m => m.Data, true))
让它成为助手
这比我最初预期的要复杂一些,但可以做到,只需将以下代码添加到您选择的cshtml文件中的App_Code文件夹中即可。由于您不能在辅助函数中使用泛型,因此您必须在@function { }块中创建一个具有正确签名的实际函数。
@using System.Linq.Expressions
@using System.Web.Mvc;
@using System.Web.Mvc.Html;
@functions
{
public static HelperResult SwitchFor<TModel, Object>(HtmlHelper<TModel> html, Expression<Func<TModel, Object>> func, Boolean wrap)
{
var data = html.TextAreaFor(func);
return WrapItUp(data);
}
}
@helper WrapItUp(MvcHtmlString data)
{
<div class="helloworld">
@(data)
</div>
}
打个电话,差不多
您必须将键入的 HtmlHelper 实例传递给您的模型。
@(Html.SwitchFor(Html, m => m.Data, true))
顺便说一句,这很棒!它将帮助我以更自然的方式布置多列表单。我很高兴遇到您的挑战,因为这是我自己没想到的解决方案。
祝你好运,玩得开心!
我在这里找到了一些帮助:
一些简单的示例代码:
public static class HtmlHelperExtensions
{
public static MvcHtmlString SwitchSlider(this HtmlHelper helper, bool value)
{
return new MvcHtmlString("<div>html i want to output here</div>");
}
}
它允许您这样做:
@Html.SwitchSlider(true);
我仍然不确定如何复制 TextBox For之类的内容并传入 x => x.param