Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 how to use @<text></text> as html helper parameter

I'm a little lost with the creation of an MVC3 Helper. I have my helper that just create a row with an expression that is passed as parameter.

I want to use my htmlHelper like this:

@Html.AddTableFormField(model => model.UserName, @<text>
        @Html.EditorFor(m => m.UserName)<span class="warning">Use only letters</span>
    </text>)

This is my HtmlHelper (some irrelevant code was removed):

public static MvcHtmlString AddTableFormField<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> property, Expression<Func<TModel>> customFormat = null)
    {
        var metadata = ModelMetadata.FromLambdaExpression(property, htmlHelper.ViewData);

        string displayName = metadata.DisplayName;

        var propName = metadata.PropertyName;

        if (string.IsNullOrWhiteSpace(displayName))
            displayName = propName;

        MvcHtmlString htmlCustomFormat = null;

        if (customFormat != null)
        {
            var deleg = customFormat.Compile();
            htmlCustomFormat = new MvcHtmlString(deleg().ToString());
        }
        else
            htmlCustomFormat = htmlHelper.EditorFor(property);

        return new MvcHtmlString(string.Format("<tr>"+
                "<td class=\"form-label\">"+
                    "<label class=\"editor-label\" for=\"{0}\">{1}<label>"+
                "</td>"+
                "<td class=\"form-data\">"+
                    "{2}"+
                "</td>"+
            "</tr>",
            propName, displayName, htmlCustomFormat));
    }

I can't even compile it, because the @<text>...</text> parameter is invalid for the HtmlHelper because it is an 'lambda expression' and cannot be converted into Expression>

Anyone can help to solve it? I just want to pass any kind of @<text></text> to my HtmlHelper, and it just compile it and put it's MvcHtmlString into the formated return.

SOLUTION:

I found What I was looking for in this post: ASP.Net MVC3 - Pass razor markup as a parameter

The parameter type for the @<text></text> must be an Func<object, HtmlHelper> !

like image 862
IPValverde Avatar asked Aug 26 '12 20:08

IPValverde


2 Answers

I found What I was looking for in this post: ASP.Net MVC3 - Pass razor markup as a parameter

The parameter type for the @<text></text> must be an Func<object, HelperResult> !

like image 161
IPValverde Avatar answered Nov 15 '22 11:11

IPValverde


The <text>...</text> or @: is a Razor syntax (not C#) to avoid html elements, so my usggestion will be that you use string as parameter instead of @<text>

like image 26
HatSoft Avatar answered Nov 15 '22 11:11

HatSoft