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>
!
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>
!
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>
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