如何在MVC 5中创建声明性HTML帮助器

时间:2015-05-30 12:28:45

标签: asp.net-mvc-5

我的情景:

我终于开始创建自己的博客了,我正在尝试尽可能多地学习MVC。我试图在我的" PostView.cshtml"中显示我的标签作为自定义声明帮助器。文件,但我的问题是,它不是在当前的背景下,我不知道如何做到这一点。

我在SO上看了以下两个问题:

this one适用于以前版本的MVC(< = 4)和

那个提出问题并且解释不充分的人回答了{p> this one

我尝试了上述建议,但没有成功,希望有人可以帮助我。这是我的代码:

Tags.cshtml (在〜/ Views / Helpers /中):

@helper Tags(System.Web.Mvc.HtmlHelper htmlHelper,
ICollection<MyNamespace.Objects.Tag> tags)
{
    foreach (var tag in tags)
    {
        <div class="tags-div">
            @MyNamespace.Extensions.ActionLinkExtensions.TagLink(htmlHelper, tag):
        </div>
    }
}

ActionLinkExtensions.cs (在〜/ Extensions / ActionLinkExtensions /中)

namespace MyNamespace.Extensions
{
    public static class ActionLinkExtensions
    {
        public static MvcHtmlString TagLink(this HtmlHelper helper, Tag tag)
        {
            return helper.ActionLink("", ""); //logic removed for simplicity
        }
    }
}

PostView.cshtml (在〜/ Views / Shared /中)//我想使用自定义助手:

@model MyNamespace.Objects.Post
<!--extra html removed for simplicity-->
<div>
    <span>Tags:</span>@Tags(Html, Model.Tags) // '@Tags' doesn't exist in current context
</div>

我还尝试将名称空间添加到&#39;〜/ Views / web.config&#39;:

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="MyNamespace" />
    <add namespace="MyNamespace.Extensions" />
  </namespaces>
</pages>

我的全名&#34;为我的&#34; Tag.cs​​&#34; class是MyNamespace.Objects.Tag和&#34; Post&#34; .cs&#34;是MyNamespace.Objects.Post

任何有关答案的解释和建议也将非常感谢,非常感谢您提前。

2 个答案:

答案 0 :(得分:1)

我决定尝试使用MVC3方式,我手动添加了App_Code文件夹,并按照this great article中的步骤操作。 它工作正常,我需要重新启动Visual Studio以使我的Intellisense工作(这延长了我的解决方案)。

我删除了文件夹'〜/ Views / Shared /'

我在App_Code文件夹中添加了一个文件MyHelpers.cshtml,在我添加了帮助方法的文件中:

@helper Tags(System.Web.Mvc.HtmlHelper htmlHelper,
    ICollection<MyNamespace.Objects.Tag> tags)
{
    foreach (var tag in tags)
    {
        <div class="tags-div">
            @MyNamespace.Extensions.ActionLinkExtensions.TagLink(htmlHelper, tag)
        </div>
    }
}

并在我的PostView.cshtml中称之为:

@MyHelpers.Tags(Html, Model.Tags)

Viola按预期工作......希望这可以帮助那些最终陷入这种情况的人......

答案 1 :(得分:0)

我认为更好更简单的方法是为您定义一个显示模板。标签集合将放在~Views/Shared/DisplayTemplates中:

@model ICollection<MyNamespace.Objects.Tag>

foreach (var tag in Model)
{
    <div class="tags-div">
        @MyNamespace.Extensions.ActionLinkExtensions.TagLink(htmlHelper, tag)
    </div>
}

PostView.cshtml中,您只需写下:

@Html.DisplayFor(model => model.Tags)