开发者

Accessing Model object in a custom Html helper

开发者 https://www.devze.com 2023-01-25 08:44 出处:网络
I\'m trying to create a custom HTML helper and I would li开发者_如何学Goke to know how I can access the Model object without passing it as a parameter.

I'm trying to create a custom HTML helper and I would li开发者_如何学Goke to know how I can access the Model object without passing it as a parameter.

Thanks


If you are using strongly typed views which you should:

public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> htmlHelper)
{
    TModel model = htmlHelper.ViewData.Model;
    return MvcHtmlString.Empty;
}

If you are not using strongly typed views which you shouldn't:

public static MvcHtmlString MyHelper(this HtmlHelper htmlHelper)
{
    object model = htmlHelper.ViewData.Model;
    return MvcHtmlString.Empty;
}


HTML helpers are a bad way to generate HTML programmatically. Web Forms is much better with code in a page class file and HTML markup in a separate file. Yes HTML helpers put some code in separate class files but you are calling code from your HTML page. Whats to stop you from writing code directly in your view page. MVC is supportive of lots of bad practices which you don't have to do but for some reason in Web Forms developers have to do bad practices because it is allowed. If you learn Web Forms well, you will develop maintainable and scalable web applications using modern object oriented patterns instead of procedural logic like HTML helpers.

0

精彩评论

暂无评论...
验证码 换一张
取 消