I guess what I want to do is "chain" my data down so that it ends up looking the same. All my html must be wrapped in some form of
<fieldset class="" data-role="">
So what I have is a helper that prints the various forms. One would be a label:
<fieldset data-role="@role">
<label>@Html.Raw(label)</label>
</fieldset>
Now when I have multiple types of labels, and one includes being a code block. When it is a simple piece of text, like "First Name" I do:
@FieldSet.Label("First Name")
But when I have a code block such as:
<b>some text</b>
<p>some other text (some time frame - some time frame)
It becomes complicated to use this:
@FieldSet.Label("<b>" + Model.Text1 + "</b><p>" + Model.Text2 +
" (" + Model.Time1 + " - " + Model.Time2 +")</p>")
What I want it a solution that looks something like this:
@FieldSet.Label(@<text>
<b>@Model1.Text1</b>
<p>@Model.Text2 (@Model.Time1 - @Model.Time2)</p>
</text>)
I read somewhere this was possible, but I cannot find the article. I could be completely misled, but I really don't want to have a single piece of HTML in the code behind and I want to utilize the razor syntax, not string concatenation.
Check this articles from Phil Haack
You could:
Write as an extension method to a strongly-typed HtmlHelper:
public static class RazorExtensions
{
public static HelperResult Label<T>(this HtmlHelper<T> helper, Func<T, HelperResult> template) {
return new HelperResult(writer => {
writer.Write("<label>");
template(helper.ViewData.Model).WriteTo(writer);
writer.Write("</label>");
});
}
}
So you could write
@Html.Label(@<text><span>@Model.Item1<span><strong>@Model.Item2</strong></text>)
Pass Model as a parameter to your helper method
public static class FieldSet
{
public static HelperResult Label<T>(this T model, Func<T, HelperResult> template) {
return new HelperResult(writer => {
writer.Write("<label>");
template(model).WriteTo(writer);
writer.Write("</label>");
});
}
}
Usage:
@FieldSet.Label(Model, @<div><span>@Model.UserName</span><strong>@Model.FullName</strong><p>@Model.Description</p></div>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With