Custom HTML Helpers in MVC5 with Lambda Model

I am trying to create a custom HTML helper that will bring up the HTML editor in an MVC application. I followed the instructions below: http://dan.cx/2012/05/custom-strongly-typed-htmlhelpers-in-asp-net-mvc . I cannot get this to work and I am completely stuck.

Here is the HtmlHelper I created .....

public static class HTMLEditor
{


    public static HtmlString RenderFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, int? width = 810, int? height = 200)
    {
        var name = html
                    .ViewContext
                    .ViewData
                    .TemplateInfo
                    .GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

        string myEditor = "<textarea id='" + name + "' ";
        myEditor += "class='textarea' placeholder='' style='width: " + width + "px !important; height: " + height + "px !important'></textarea>";
        myEditor += "<script>$('#" + name + "').wysihtml5({'html':true,'color': false,parser: function(html) {return html;}});";
        myEditor += "editor.on('load', function() {editor.focus();editor.composer.commands.exec('insertHTML', '" + metadata.Model + "');})";
        myEditor += "</script>";
        return new HtmlString(myEditor);
    }
}

      

Then, in my Razor view, I try to use a helper helper like this ...

@HTMLEditor.RenderFor(model => model.PageDetail.HTML)

      

However, everything compiles fine, but when it comes time to render the view in the browser, I get the error:

Compilation error

Description. An error occurred while compiling a resource required to service this request. Please review the specific error details below and modify your source code accordingly.

Compiler error message: CS1501: Overload for 'RenderFor' method takes 1 argument

I'm not sure where the problem is. I see that the RenderFor method has two parameters, but I'm not sure how to pass the value of the model instance and store that value in the model instance after postback.

Any help here would be greatly appreciated.

Thanks Matt

+3


source to share


1 answer


It seems to me that you are calling. RenderFor to the wrong object.



Your RenderFor method is a HtmlHelper extension method. Therefore you must call @ Html.RenderFor (model => ...) from the view.

+7


source







All Articles