Pergunta

I have been trying to work out how to register a label extension class into a ServiceStack.Html / Razor project. I am using the "Stand-alone, self-hosted HttpListener" option but I cannot work out how to register or use new @Html extension for use in razor pages.

namespace Tribe.Guru.SelfHost
{
    public static class LabelExtensions
    {
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
        {
            return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }

            TagBuilder tag = new TagBuilder("label");
            tag.MergeAttributes(htmlAttributes);
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            tag.SetInnerText(labelText);
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }
}

Any help would be greatly appreciated, as I cannot find any documentation on it and cannot get it to work.

Foi útil?

Solução

You also need to add any namespaces to your Web.config razor configuration, e.g:

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<pages pageBaseType="ServiceStack.Razor.ViewPage">
  <namespaces>
    <add namespace="ServiceStack"/>
    <add namespace="ServiceStack.Html"/>
    <add namespace="ServiceStack.Razor"/>
    <add namespace="ServiceStack.Text"/>
    <add namespace="ServiceStack.OrmLite"/>
    <add namespace="Tribe.Guru.SelfHost"/>
  </namespaces>
</pages>
</system.web.webPages.razor>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top