ASP.NET MVC3 HtmlHelper Extension Method Like BeginForm That Uses A Partial View?
I created an extension method based on this answer to the SO question c# - How can I create a Html Helper like Html.BeginForm - Stack Overflow and it works fine. Can I move the emb
Solution 1:
I haven't found any way to move the "embedded HTML" into a partial view exactly, but a slightly more-friendly way to encapsulate the HTML in a way that provides HTML and Razor syntax highlighting and Intellisense is to move into a view helper function in a file under the app App_Code folder as described in this post on "Hugo Bonacci's Blog".
Here's my helper function:
@helper HelpTextMessage(bool isHidden, string heading, Func<object, object> content)
{
<div class="help-text @(isHidden ? "help-text-hidden" : "")">
<div class="help-text-heading">
@heading
</div>
<div class="help-text-body">
@content(null)
</div>
</div>
}
Assuming the above helper function is in a file named ViewHelpers.cshtml in the App_Code folder, it can be called in a view like this:
@ViewHelpers.HelpTextMessage(false, "Something",
@:To do something, first do something-more-specific, then do another-something-more-specific.
)
or this:
@ViewHelpers.HelpTextMessage(false, "Something",
<p>To do something, first do something-more-specific, then do another-something-more-specific.</p>
<p>Also, keep in mind that you might need to do something-else-entirely if blah-blah-blah.</p>
)
I like having the embedded HTML in a view more than I do being able to use the @using(Html.HelpTextMessage(...){ ... }
syntax, so I'm pretty happy with this as a solution.
Post a Comment for "ASP.NET MVC3 HtmlHelper Extension Method Like BeginForm That Uses A Partial View?"