Removing hashtags from URLs in MVC4 AngularJS applications within areas

After extensively researching and trying multiple examples, I am still facing an issue with my application.

I have a similar problem to this post on Stack Overflow, but the solution provided there is not working for me either.

This is the overall structure of my application:

https://i.sstatic.net/dsw6V.png

And this is the structure specific to the ADMIN AREA:

https://i.sstatic.net/NcAEp.png

The project consists of two separate applications - one for clients and one for admins. The admin section is managed through Areas.

I am using Angular 1.3.5 within the Areas.

The landing page is the index page of the Home Controller path: Areas/Admin/Views/Home/Index.cshtml

The layout is located at _Layout Path: Areas/Admin/Views/Shared/_Layout.cshtml

In the RouteConfig.cs file inside the App_Start folder:

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

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

AdminAreaRegistration.cs:

namespace StockManagment.Areas.Admin
{
    public class AdminAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new [] {"StockManagment.Areas.Admin.Controllers"}
            );
        }
    }
}

Enabled HTML5MODE to remove "#" from the URL

myApp.config(["$locationProvider", function ($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

Added Base Tag in the _Layout Page:

<base href="/">

Web.config Code For Admin Areas:

<rewrite>
  <rules>
    <rule name="Main Rule" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory"   negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

When attempting to access the admin side using this URL: http://localhost:8917/Admin/Home/Index

The website loads at localhost:8917/, and upon refreshing the page, it reverts back to the client-side home page content.

I seem to have missed something crucial in my implementation. Help would be greatly appreciated!

Edit 1:

I removed the rewrite code in web.config as I used it based on another post's suggestion.

Prior to using the following code:

myApp.config(["$locationProvider", function ($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

and

<base href="@Request.Url.AbsolutePath" />

To access the admin side homepage, the URL was: http://localhost:8917/Admin/Home/Index#/

After implementing the above code, the URL now reads: http://localhost:8917/Admin/Home/

Accessing the categories page:

Before the code adjustments, the URL was: http://localhost:8917/Admin/Home/Index#/Categories

Post changes, the URL became: http://localhost:8917/Admin/Home/Categories

However, upon refreshing the page, an error occurs:

Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or temporarily unavailable. Please ensure that the URL is correctly spelled.

Requested URL: /Admin/Home/Categories

Answer №1

It seems like you may be running into some issues with the rewrite rule in your current setup. This could potentially cause conflicts with the MVC routing system. My recommendation would be to take out the URL rewrite rule from the web.config file.

If your goal is to have a set of routes that all point to the Index action in the admin area (to route various URLs to your Angular SPA), you might want to consider using a wildcard MVC route instead.

For example, you can create a route override specifically designed to work seamlessly with AngularJS and HTML5 routing:

context.MapRoute(
    name: "Application1Override",
    url: "Application1/{*.}",
    defaults: new { controller = "Application1", action = "Index" }
);

Answer №2

In your original issue, the initial problem you encountered was:

<base href="/" />

This code informs angular that the base routing is "/", so when you refresh the page, MVC will take you back to the root action "/".

By changing this to -

<base href="@Request.Url.AbsolutePath" />

Angular will recognize that the base of this page is the current {action}/{controller}.

Now, another issue arises with the routing:

namespace StockManagment.Areas.Admin
{
    public class AdminAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Admin";
            }
        }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Admin_default",
            "Admin/{controller}/{action}/{id}", // Your current URL= /Admin/Home/Categories -- which means id = Categories
            new { action = "Index", id = UrlParameter.Optional },
            new [] {"StockManagment.Areas.Admin.Controllers"}
        );
    }
}}

If you do not need an ID, you can use the following code:

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Admin_default",
            "Admin/{controller}/{action}/{*angular}",
            new { action = "Index",
            new [] {"StockManagment.Areas.Admin.Controllers"}
        );
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come it's so difficult to set the perspective camera to accurately display sizes in three js?

Currently, I am using Three Js to create a visual representation of a car. However, I am encountering an issue with the perspective camera that I can't seem to resolve. My goal is to make it appear more realistic by only showing the front of the car, ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

I wish to exchange information between two components that have no connection with each other

Check out my folder organization: Top-navigation Side-navigation This screen features selectors for both top and side navigation. I need to transfer the title from the side navigation to the top navigation. ...

Personalized text field in date selector using Material UI

Hey there, I've been incorporating Material UI into my react project, specifically utilizing their recommended Material UI Pickers for a date picker. In order to maintain consistency with the rest of my form fields, I'm attempting to customize th ...

The data sent to the controller through AJAX is empty

I am facing an issue while trying to return a List of objects back to my controller. The problem is that the list appears as null when it reaches the controller. Below is the structure of what I am doing: Controller Action Signature [HttpGet] public Acti ...

What is the best way to control the number of fetch calls sent to an endpoint service ensuring that only a maximum of 10 calls are made every second?

Is there a way to prevent the browser from encountering the "Error 429 Too Many Requests" by adjusting the code below to ensure that no more than 10 calls per second are made? Please note that the rate limit of 10 calls per second is set by a 3rd-party AP ...

Incorporate JSON data into a subsequent AJAX call when coding in JavaScript

I am facing an issue where I need to use data returned from an ajax request to construct a string and then post it back using ajax. However, the variable I'm assigning the data to is not within the scope of the second request, resulting in a 'var ...

Passing a dynamic data value to a click event in Google Analytics

I need help finding a solution for this issue. My goal is to track an event in Google Analytics through an onclick event, but I am struggling with passing a dynamic variable to the URL field. Below is the code snippet: <asp:hyperlink ID="Hyperlink2" r ...

What is the correct way to add a library to webpack configuration?

Currently, I am working with Rails 6 and webpack in my project. I am interested in integrating the library jquery-textcomplete, but I am unsure about how to properly include it in the application.js file. Here are the steps I have taken so far: I instal ...

App interface automatically redirecting user back to login page post-login

Hello, I have been working on Selenium C# and have successfully implemented some methods using pagefactory. However, I am facing an issue where the application opens a new instance of the login page after logging in. How can I ensure that only a single lo ...

What could be causing the response data from an AJAX request to be in error instead of success?

My JSON data is securely stored on , and I can access it through a unique URL. Here is the specific URL: The JSON data found at the above URL is: { "glossary": { "title": "Suyog", "GlossDiv": { ...

Bootstrap Progress Animation Not Scaling Properly

I am encountering an issue with my Bootstrap 2.3 progress bars. They are supposed to show async file reads and be animated by updating their CSS properties using jQuery. However, the problem I'm facing is that the scale seems to be off - when the prog ...

Output the keycode to the console repeatedly

I'm currently facing a minor mental obstacle: I have a javascript function embedded in html that displays the keycode when a key is pressed. It's connected to a function that provides detailed information about the character and keycode being pre ...

Using jQuery to select a nested element in HTML

After choosing $("a.tp[programm='" + programm + "']"); I am looking to target the nested element span.thump and update its text content. How can I achieve this? <h4><a programm="74" class="tp" href="#"><img src="/images/tuo.png ...

Switch from Index.html to Index.html#section1

Currently, I am working on a website and sending someone a draft for review. However, the Home screen is designed as a 'a href' link with "#home". The issue arises when the website opens from my computer; it goes to ...../Index.html instead of .. ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

How can I adjust the number of columns displayed per page on a Bootstrap Studio website?

Currently, I am utilizing Bootstrap studio to design a website featuring multiple cards on each page. Initially, I incorporated cards from the sb-admin-2 template and everything was proceeding smoothly. In my bootstrap studio interface, the three-column ca ...

Is it possible for an AJAX request to return both HTML data and execute callback functions simultaneously?

Is it possible to update the content of an HTML div and call a JavaScript function with specific parameters obtained through AJAX after the completion of the AJAX request, all within a single AJAX call? ...

Plugin for jQuery that smoothly transitions colors between different classes

After searching through numerous jQuery color plugins, I have yet to discover one that allows for animating between CSS class declarations. For instance, creating a seamless transition from .class1 to .class2: .class1 { background-color: #000000 } .class ...