简体   繁体   中英

ASP.NET MVC Razor Helper with @HTML in App_Code

I try to make a Helper inside App_Code in cshtml File.

// 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>
}

I don't know if that is possible. I have some errors:

  • @Html don't know LabelFor, but i put the using on top

  • Maybe Func as parameter is wrong

No, this is not possible. You could write a normal HTML helper with @Html.LabelFor because that your view is strongly typed .The typed @Html.LabelFor will generate your lable for you. This is usually just the property name but for properties of complex type and it will allow you to use compile time checking.

you can do some thing like this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM