drewwyatt
drewwyatt

Reputation: 6027

How can I use Angular views inside of an ASP.Net MVC 4 application?

I would like to use Angular.JS to implement multiple contact forms, but am not sure how to keep angular's routing from interfering with ASP.Net's routing.

My ASP.Net MVC 4 routes look like this (this is the default project with minor alterations):

namespace Angular_Test
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{action}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

I would like my contact page's (located at /contact) ng-view div to default to something like (say) form.html, and have a handful of links that would load in form2.html, form3.html, etc. But would pointing those links to something like /contact/form2 totally screw with ASP.Net's routes? How should I go about implementing this?

Upvotes: 1

Views: 558

Answers (2)

trevorc
trevorc

Reputation: 3031

I prefix my angular view routes with '/partials'. It looks like this.

routes.MapRoute(
     "DefaultPartials",
     "partials/{controller}/{action}/{id}",
     new { id = UrlParameter.Optional});

Now keep in mind that this approach will cause a partial view to go through the entire page life cycle but I use razor partials for localization of my page text so this is ok for my usage.

Then I use areas in my application to spit out JSON data from Web API controllers for angular to consume. Keeps things nice and tidy. Hope this helps.

I almost forgot. You will want to put the partials route just before the standard default route in RouteConfig.cs.

Upvotes: 1

Michał Dudak
Michał Dudak

Reputation: 5058

You have to ensure that all URLs mapped to Angular views are handled by the same route on the server (i.e. server should return /contact if it gets a request to either /contact, /contact/form1, /contact/form2, etc.)

Upvotes: 1

Related Questions