Create Html in Html Helper using Razor or Tag Builder?

I am creating Html Helper in MVC 4 and I want to know how to create / html tags correctly in html helpers.

For example, here is a simple html helper that creates an image tag using the TagBuilder class:

 public static MvcHtmlString Image(this HtmlHelper html, string imagePath, string title = null, string alt = null) { var img = new TagBuilder("img"); img.MergeAttribute("src", imagePath); if (title != null) img.MergeAttribute("title", title); if (alt != null) img.MergeAttribute("alt", alt); return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing)); } 

On the other hand, I can do something like this:

 // C#: public static MvcHtmlString Image(this HtmlHelper html, string imagePath, string title = null, string alt = null) { var model = new SomeModel() { Path = imagePath, Title = title, Alt = alt }; return MvcHtmlString.Create(Razor.Parse("sometemplate.cshtml", model)); } // cshtml: <img src="@model.Path" title="@model.Title" alt="@model.Alt" /> 

What is the best solution?

+6
source share
2 answers

Both are valid, I would suggest that the latter will be much slower, and I'm trying to figure out what advantages it could use using the Partial View.

My rule is that HtmlHelpers should only be used for simple markup; The use of Partial Views and Action with Children should be increasingly complex.

+3
source

The first method works with strings in memory and executes, the latter is more expensive in terms of resources and makes access to the file.

0
source

Source: https://habr.com/ru/post/951660/


All Articles