English 中文(简体)
Creating a Web Navigation Helper Class for MVC
原标题:

Im a newbie to MVC and trying to use the web navigator class in my MVC application. http://polymorphicpodcast.com/shows/webnavigator/ The class enables us to have stongly typed urls in a central class file.

I have 3 questions:

  1. Is this the best way of storing strongly typed urls in MVC or does
    MVC has some special helper methods which does the same thing.

  2. What is the best place for the class file to go in e.g VIEW/MODEL or
    CONTROLLER

  3. Below is a sample of the Navigation class which returns a proper url for an image file. Instead of passing the UrlHelper object to the I want to run this class in the System.Web.Mvc.ViewPage context (current context). What is the best way of doing this.

Sample navigator class for images:

using System.Web;
using System.Web.Mvc;

public class IMG
{
    public string AjaxLoading(UrlHelper urlHelper)
    {
        return urlHelper.Content("~/Images/loading2.gif");
    }
}
最佳回答

To answer your questions:

  1. There are many ways to create navigation links for you ASP.NET MVC, whatever works for you is the best.

  2. Most would answer that class files should be placed in Model folder. I found it more meaningful to place ViewModel classes in a separate folder and classes used throughout the application (business logic/meat of the application) in a separate file.

  3. What you re trying to accomplish seems like a job for extension methods. Here is a good tutorial: http://www.dotnetcurry.com/ShowArticle.aspx?ID=406&AspxAutoDetectCookieSupport=1

What you re doing is on the right track, however, you need to create static classes and static functions/methods for this to work properly.

http://msdn.microsoft.com/en-us/library/bb383977.aspx has some general info on extension methods.

One quick note: To allow usage of all the extension methods you create, you ll need to reference the class/namespace that you placed them in.

There are two methods of doing this:

  1. Assuming you ve placed your extension methods in MvcApplication1.MyExtensionMethods, Add the following after the

      <page>
          <namespaces> 
    

    tag in your application s web.config (Not the View s web.config file)

         <add namespace="MvcApplication1.MyExtensionMethods"/>
    

    Doing so will allow the extension methods to be used in all of your views (.aspx/.ascx) files.

  2. Place

      <%@ Import Namespace="MvcApplication1.MyExtensionMethods" %>
    

    at the top of your .aspx/.ascx files. You would need to do this for every file you need to use the extension methods on (not efficient)

The following is what I implement and it has served me well thus far.

NavigationLink.cs

   public class NavigationLink
   {
        string Text {get; set;}
        RouteValueDictionary Routes {get; set;}
        string RouteName {get; set;}
   }

NavigationLink.ascx (Place in shared folder for easy access in entire application)

(Note: I wrap the links in < li> < /li> tags because I use lists for all my navigation controls. You can then place these links in any type of list, allowing freedom with the list s class/style.)

   <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<NavigationLink>>">

   <% foreach(NavigationLink n in Model){ %>
      <li>
          <a href="<%= string.IsNullOrEmpty(n.RouteName) ? Url.RouteUrl(Routes) : Url.RouteUrl(RouteName) %>">
         <%= n.Text %>
        </a>
      </li>
   <% } %>

Menus.cs (Some examples)

  public static Menus
  {
       public static List<NavigationLink> MainMenu()
       {
           List<NavigationLink> links = new List<NavigationLink>();
           links.Add(new NavigationLink{
              Text = "Home",
              Routes = new RouteValueDictionary(new { action="Index", controller="Home" })
           });
           return links;
       }

       public static List<NavigationLink> UserMenu()
       {
           List<NavigationLink> links = new List<NavigationLink>();
           links.Add(new NavigationLink{
              Text = "Messages",
              Routes = new RouteValueDictionary(new { action="Messages", controller="UserCP" })
           });
           links.Add(new NavigationLink{
              Text = "Account",
              Routes = new RouteValueDictionary(new { action="Account", controller="UserCP" })
           });
           return links;
       }

  }

Now that you have everything setup, calling these functions is simple:

In your view file (.aspx/.ascx)

  <ul class="horizontal_menu">
      <% Html.RenderPartial("NavigationLink", MyMvcApplication1.Menus.MainMenu()) %>
  </ul>

Having it setup like this allows for different partial views to be created to render out lists of navigation links in different ways and would require that you only build the partial and call it.

问题回答

暂无回答




相关问题
WebForms and ASP.NET MVC co-existence

I am trying to make a WebForms project and ASP.NET MVC per this question. One of the things I ve done to make that happen is that I added a namespaces node to the WebForms web.config: <pages ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

Create an incremental placeholder in NHaml

What I want to reach is a way to add a script and style placeholder in my master. They will include my initial site.css and jquery.js files. Each haml page or partial can then add their own required ...

asp.net mvc automapper parsing

let s say we have something like this public class Person { public string Name {get; set;} public Country Country {get; set;} } public class PersonViewModel { public Person Person {get; ...

structureMap mocks stub help

I have an BLL that does validation on user input then inserts a parent(PorEO) and then inserts children(PorBoxEO). So there are two calls to the same InsertJCDC. One like this=>InsertJCDC(fakePor)...

ASP.NET MVC: How should it work with subversion?

So, I have an asp.net mvc app that is being worked on by multiple developers in differing capacities. This is our first time working on a mvc app and my first time working with .NET. Our app does not ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

热门标签