【问题标题】:ASP.NET MVC Razor Helper with @HTML in App_CodeApp_Code 中带有@HTML 的 ASP.NET MVC Razor Helper
【发布时间】:2017-05-11 07:03:00
【问题描述】:

我尝试在 cshtml 文件中的 App_Code 中创建一个 Helper。

// Using's are needed to ensure helpers function correctly.
@using System.Web.Mvc;
@using System.Web.Mvc.Html;
@using System.Web.Mvc.Routing;
@using System.Web.Mvc.Razor;
@functions {
    private static WebViewPage page { get { return PageContext.Page as WebViewPage; } }
    private static System.Web.Mvc.HtmlHelper<dynamic> html { get { return page.Html; } }
    private static UrlHelper url { get { return page.Url; } }
    private static dynamic viewBag { get { return page.ViewBag; } }
}

@helper HelperName(Func<dynamic, dynamic> expression)
{
    <div class="form-group">
        @Html.LabelFor(model => expression, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.EditorFor(model => expression, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => expression)
        </div>
    </div>
}

我不知道这是否可能。我有一些错误:

  • @Html 不知道 LabelFor,但我把 using 放在最上面

  • 可能 Func 作为参数是错误的

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

不,这是不可能的。您可以使用@Html.LabelFor 编写一个普通的HTML 帮助程序,因为您的视图是强类型的。键入的@Html.LabelFor 将为您生成标签。这通常只是属性名称,但对于复杂类型的属性,它将允许您使用编译时检查。

你可以做一些类似this回答的事情。

【讨论】:

    猜你喜欢
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2014-03-15
    相关资源
    最近更新 更多