开发者

VB.Net, MVC3, and Razor - Modifying ActionLink Helper

开发者 https://www.devze.com 2023-03-14 07:15 出处:网络
Question: How do I modify or create my own Html.ActionLink helper to accept and handle the first parameter (linkText) passed in as an empty string / nothing?

Question: How do I modify or create my own Html.ActionLink helper to accept and handle the first parameter (linkText) passed in as an empty string / nothing?

Details: I currently have a strongly typed view that's passed a model which contains search开发者_如何学Go results. My view loops through each item in the model and attempts to display a link to a contact with the following code:

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

Normally this would work just fine, but not every item in my search result has a ContactName. The Html.ActionLink helper errors when this first parameter is empty. In case it helps, here's the model property for ContactName (which is generated from a template due to Database First, so I don't believe it can be modified):

Public Property ContactName As String

I'd like to have a helper function that simply returns nothing if the ContactName is an empty string / nothing.

I'm guessing I need to extend this helper, and I've struggled to find any good, up-to-date resources in VB.net for extending helper functions. Other approaches are more than welcome if they're considered best practice. I'm working in VB.net, MVC3, and Razor in the ASP.net 4.0 framework. Thanks in advance for your help!


To make this happen, I created a Helpers folder in my solution and added a new module HtmlHelperExtensions.vb which is detailed here (thanks to Darin Dimitrov for the module code):

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

I then had to go into my Web.Config file located in the View folder of my solution in order to add this as a common view namespace, added as namespace="solutionname.namespace" (note the last add namespace tag):

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

I then had to close and reopen my views (.vbhtml) for intellisence to work for my new html helper.


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

and then:

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


If you want to get this kind of result in MVC View Using @Html.ActionLink :

<a href="#"><i class="fa-editico"></i></a>

See This example image and read below: https://lh5.googleusercontent.com/-5xihbu8wIkY/VJQMq9Y6foI/AAAAAAAAAK4/LNPlbibLEPo/w506-h281/LINK.JPG

I hope this code example will help you, I test this code and everything is working well. good luck :)

MVC Helper:

   //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 View:

//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 !");"
            })
0

精彩评论

暂无评论...
验证码 换一张
取 消