I am trying to create a custom HTML helper that will result in an HTML editor appearing in an MVC app. I have been following the instructions at: http://dan.cx/2012/05/custom-strongly-typed-htmlhelpers-in-asp-net-mvc. I cannot get this to work and am completely stuck.
Here is the HtmlHelper that I have 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 am attempting to use the helper like such...
@HTMLEditor.RenderFor(model => model.PageDetail.HTML)
However, everything compiles okay but when it comes time to render the view to the browser, I am receiving an error :
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1501: No overload for method 'RenderFor' takes 1 arguments
I am not sure where the problem lies. I do see that the RenderFor method has two parameters, but I am unsure how to pass in a model instance value and have that value retained in the model instance after postback as well.
Any help here would be greatly appreciated.
Thanks Matt
string name = ExpressionHelper.GetExpressionText(expression);and you should consider usingTagBuilderto generate your html.