【问题标题】:VB.Net, MVC3, and Razor - Modifying ActionLink HelperVB.Net、MVC3 和 Razor - 修改 ActionLink Helper
【发布时间】:2011-06-21 19:26:43
【问题描述】:

问题:如何修改或创建自己的 Html.ActionLink 帮助程序以接受和处理作为空字符串/空传入的第一个参数 (linkText)?

详细信息:我目前有一个强类型视图,它传递了一个包含搜索结果的模型。我的视图循环遍历模型中的每个项目,并尝试使用以下代码显示指向联系人的链接:

@Html.ActionLink(currentItem.ContactName, "contact", "details", New With { .id = currentItem.ContactID }, Nothing)

通常这可以正常工作,但并非我的搜索结果中的每个项目都有联系人姓名。当第一个参数为空时,Html.ActionLink 帮助程序出错。如果有帮助,这里是 ContactName 的模型属性(由于 Database First,它是从模板生成的,所以我不相信它可以修改):

Public Property ContactName As String

我想要一个辅助函数,如果 ContactName 是一个空字符串/什么都没有,它什么都不返回。

我猜我需要扩展这个助手,我一直在努力在 VB.net 中找到任何好的、最新的资源来扩展助手功能。如果其他方法被认为是最佳实践,则非常受欢迎。我在 ASP.net 4.0 框架中的 VB.net、MVC3 和 Razor 中工作。提前感谢您的帮助!

【问题讨论】:

    标签: vb.net asp.net-mvc-3 razor html-helper


    【解决方案1】:

    为了实现这一点,我在我的解决方案中创建了一个 Helpers 文件夹并添加了一个新模块 HtmlHelperExtensions.vb,此处详细介绍了该模块(感谢 Darin Dimitrov 提供的模块代码):

    Imports System.Runtime.CompilerServices
    
    Namespace MyHtmlHelpers
    Public Module HtmlHelperExtensions
        'Function to extend the ActionLink helper
        'Function will return an empty html string for empty or null linkText values
        <Extension()> _
        Public Function MyActionLink(
                ByVal html As HtmlHelper            , _
                ByVal linkText As String            , _
                ByVal actionName As String          , _
                ByVal controllerName As String      , _
                ByVal routeValues As Object         , _
                ByVal htmlAttributes As Object
            ) As IHtmlString
    
            If String.IsNullOrEmpty(linkText) Then
                Return MvcHtmlString.Empty
            End If
    
            Return html.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes)
        End Function
    End Module
    End Namespace
    

    然后我必须进入位于我的解决方案的 View 文件夹中的 Web.Config 文件,以便将其添加为公共视图命名空间,添加为 namespace="solutionname.namespace"(注意最后添加命名空间标签) :

    <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <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.Routing" />
        <add namespace="BrokerCRM.MyHtmlHelpers" />
      </namespaces>
    </pages>
    

    然后我不得不关闭并重新打开我的视图 (.vbhtml) 以便智能为我的新 html 助手工作。

    【讨论】:

      【解决方案2】:
      Module HtmlLinkExtensionsModule
          <System.Runtime.CompilerServices.Extension()> _
          Public Function MyActionLink(html As HtmlHelper, linkText As String, actionName As String, controllerName As String, routeValues As Object, htmlAttributes As Object) As IHtmlString
              If String.IsNullOrEmpty(linkText) Then
                  Return MvcHtmlString.Empty
              End If
              Return html.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes)
          End Function
      End Module
      

      然后:

      @Html.MyActionLink(currentItem.ContactName, "contact", "details", New With { .id = currentItem.ContactID }, Nothing)
      

      【讨论】:

      • 我尝试在我的视图中使用 MyActionLink 无济于事。 “MyActionLink 不是‘System.Web.Mvc.HtmlHelper(Of BrokerCRM.SearchResultViewModel)’的成员。我尝试在模块周围放置一个命名空间,并在我的视图中使用@Using 语句引用它。我还尝试将我的模块公开. 我还在视图周围留下了命名空间,并将我的命名空间添加到 View Web.Config 文件的正确位置:''。任何方向将不胜感激。
      • @Justin,恐怕我的 VB.NET 生锈了。我发布的代码是由我的原始 C# 版本的自动 C# 到 VB.NET 转换工具生成的。所以也许下面的文章:asp.net/mvc/tutorials/creating-custom-html-helpers-vb 会给你指导如何在 VB.NET 中正确地做到这一点。
      【解决方案3】:

      如果你想在 MVC 视图中使用 @Html.ActionLink 获得这种结果:

      &lt;a href="#"&gt;&lt;i class="fa-editico"&gt;&lt;/i&gt;&lt;/a&gt;

      请参阅此示例图片并阅读以下内容:https://lh5.googleusercontent.com/-5xihbu8wIkY/VJQMq9Y6foI/AAAAAAAAAK4/LNPlbibLEPo/w506-h281/LINK.JPG

      希望此代码示例对您有所帮助,我测试了此代码,一切正常。祝你好运:)

      MVC 助手:

         //iElementClassName = <i> - element class 
      public static MvcHtmlString ActionLinkCustom(this HtmlHelper htmlHelper, string iElementClassName, string action, string controller, object routeValues, object htmlAttributes)
      {
          var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
          //get array of HTML attributes
          var attributes = AnonymousObjectToKeyValue(htmlAttributes);
          //create <a> - Tag
          var anchor = new TagBuilder("a");
          //add <i> tag inside in "<a> <a/>" Tag
          anchor.InnerHtml = string.Format("<i class='{0}'></i>", iElementClassName);
          //Make Href attribute 
          anchor.MergeAttribute("href", urlHelper.Action(action, controller, routeValues));
          //add array of attributes
          anchor.MergeAttributes(attributes, true);
      
          return MvcHtmlString.Create(anchor.ToString());
      }
      
      //It helps to generate attribute's array 
      private static Dictionary<string, object> AnonymousObjectToKeyValue(object anonymousObject)
      {
          var dictionary = new Dictionary<string, object>();
      
          if (anonymousObject == null) return dictionary;
      
          foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
          {
              dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));
          }
      
          return dictionary;
      }
      

      MVC 视图:

      //When user click edit css icon, MVC Controller gets Id and we see Alert message
      //fa-edit - This is a CSS class name 
      
      @Html.ActionLinkCustom("fa-editico","ActionName", "ControllerName", new { Id = Model.Id},
                  new
                  {
                      title = "Edit Button",
                      onclick = "alert("It Works !");"
                  })
      

      【讨论】:

        猜你喜欢
        • 2012-03-28
        • 2011-11-04
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多