Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor Helpers sharing html problem with code blocks

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.

like image 572
BradLaney Avatar asked Aug 01 '11 21:08

BradLaney


1 Answers

Check this articles from Phil Haack

  • http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx
  • http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx

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>)
like image 165
Vasea Avatar answered Sep 18 '22 14:09

Vasea