Select .state on page reload angularjs(using angular-ui-router) - asp.net-mvc

I am developing a ASP.NET MVC 5 application. I am loading a partial view through angular 'ui.router' on a div in a parent page. Routing is working great until I refresh the page - than a partial view is loading on a whole page but I want it to still load as a partial.
This is my code. A parent view, FirstPage.cshtml:
<html ng-app="myApp">
<head>
<base href="/">
<title>First Page</title>
<script src="/Scripts/Angular/angular.js"></script>
<script src="/Scripts/Angular/angular-ui-router.js"></script>
<script src="/Scripts/app.js"></script>
</head>
<body>
<h1>First Page</h1>
<ul id="myMenu">
<li ui-sref="customer">Customer</li>
</ul>
<div ui-view="containerOne"></div>
</body>
</html>
This is my app.js:
var myApp = angular.module("myApp", ['ui.router']);
var proposalConfig = function ($stateProvider, $locationProvider) {
$locationProvider.hashPrefix('!').html5Mode(true);
$stateProvider
.state('customer', {
url: 'Proposal/Customers',
views: {
"containerOne": {
templateUrl: '/Proposal/Customers'
}
}
});
}
proposalConfig.$inject = ['$stateProvider', '$locationProvider'];
myApp.config(proposalConfig);
My RouteConfig.cs:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "ProposalCustomers",
url: "Proposal/Customers",
defaults: new { controller = "Proposal", action = "Customers" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
My ProposalController.cs:
public ActionResult Customers()
{
return View();
}
public ActionResult FirstPage()
{
return View();
}
My Views/Proposal/Customers.cshtml:
<h2>Customer list</h2>
I hope my problem is clear.
EDIT:
I changed my RouteConfig.cs following the solution from this article:
http://www.codeproject.com/Articles/806500/Getting-started-with-AngularJS-and-ASP-NET-MVC-P
to have a default route like this:
routes.MapRoute(
name: "Default",
url: "{*url}",
defaults: new { controller = "Proposal", action = "FirstPage" }
When I refresh a page that has a route exactly like my controller/action, it still loads that specific route on a whole page instead as a partial. If I change a .state url to something else page refresh is working. But still if I put manually a controller/action path in the URL, it shows a view on a whole page instead as a partial.
Is there a way to avoid this?

You need to change you ng-view to ui-view as you are using angular $stateProvider not angular $routeProvider
HTML
<body>
<h1>First Page</h1>
<ul id="myMenu">
<li ui-sref="customer">Customer</li>
</ul>
<div ui-view=""></div>
</body>
You stateProvider should be change which is currently using single view and you declared it as like you are using nested-views
Config
var myApp = angular.module("myApp", ['ui.router']);
var proposalConfig = function($stateProvider, $locationProvider, $urlRouterProvider) {
$locationProvider.hashPrefix('!').html5Mode(true);
$urlRouterProvider.otherwise('/Proposal/Customers'); //default redirection if no route matched
$stateProvider.state('customer', {
url: '/Proposal/Customers',
templateUrl: '/Proposal/Customers',
controller: 'someController' //if you want
});
}
proposalConfig.$inject = ['$stateProvider', '$locationProvider'];
myApp.config(proposalConfig);
Hope this could help you, Thanks.

Ok, so what I'm guessing is happening is you mapped a route in your MVC application to serve the same route as your angular application, in this instance, you mapped 'Proposal/Customers' in your MVC router and in your Angular-UI-Router.
So what is happening is that if you're already in your Angular application, the Angular router has control and as you navigate around, it is loading the template as a child template and putting the HTML into the correct location. When you refresh, you're sending that route to the MVC router, though, and it's serving the HTML as the page.
EDIT
Forgot to mention, this is happening because you've got html5 routing turned on.

Related

ASP.NET MVC - keep links to the root folder

I am trying to link inside the same folder, I have the following structure
/Home/Index
/Home/About
/Home/Contact
When I start the webpage, I link to the Index, so I get the webpage on the screen: www.example.com.
Now I would like to link to another page so I get: www.example.com/Contact.html (or even better I would like to get www.example.com/Contact) however I get www.example.com/Home/Contact.
I use this as an action link:
<li class="pure-menu-item pure-menu-selected">#Html.ActionLink("Contact us", "Contact", "Home")</li>
This is my route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What could I change to get the desired result?
Decorate you Contact action with a RouteAttribute and pass it the desired route as parameter (i.e. "Contact")
Edit
Here's an example HomeController using the RouteAttribute:
public class HomeController
: Controller
{
public IActionResult Home()
{
return this.View();
}
[Route("Contact")]
public IActionResult Contact()
{
return this.View();
}
}
Note that you can use the RouteAttribute on Controllers, too. For instance, if I added a Route("Test") attribute on the HomeController, all of my controllers actions would look like: "/Test/[ActionRoute]".
In your views, you can use the following syntax, instead of using the old #Html.ActionLink tag helper:
<li class="pure-menu-item pure-menu-selected">
<a asp-controller="Home" asp-action="Contact">Contact Us</a>
</li>
In my opinion, those attribute tag helpers are way cleaner and html friendly ;)
i was able to fix it with some good reading and searching and this is what i came up with:
i added this to the routeConfig for each link to a html page:
routes.MapRoute("Index", "Index", new { controller = "Home", action = "Index" });
routes.MapRoute("About", "About", new { controller = "Home", action = "About" });
routes.MapRoute("Contact", "Contact", new { controller = "Home", action = "Contact" });
and instead of using an action link i use a route link:
<li class="pure-menu-item">#Html.RouteLink("About us", "About")</li>
this gives the desired result: www.example.com/About

AngularJS routing Issues $injector:modulerr

Ok so I am fairly new at AngularJS and just running through a demo, but I am having issues with the routing side of things and can't figure it out. I thought you guys would know instantly that I have done something dumb.
So here goes.
This is my JS file
var WebApplication2 = angular.module('WebApplication2', ['ng-route']);
WebApplication2.controller('LandingPageController', LandingPageController);
WebApplication2.config([
'$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/routeOne', {
templateUrl: 'routesDemo/one'
})
.when('/routeTwo', {
templateUrl: 'routesDemo/two'
})
.when('/routeThree', {
templateUrl: 'routesDemo/three'
});
}
]);
And here is my html code
<html ng-app="WebApplication2" ng-controller="LandingPageController">
<head>
<title ng-bind="models.helloAngular"></title>
</head>
<body>
<h1>{{models.helloAngular}}</h1>
<ul>
<li>Route One</li>
<li>Route Two</li>
<li>Route Three</li>
</ul>
<div ng-view></div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
#Scripts.Render("~/bundles/AngularBundle")
</body>
</html>
I also have this js controller file
var LandingPageController = function ($scope) {
$scope.models = {
helloAngular: 'I work!'
};
}
I then have a controller with the following actionresults
public class RoutesDemoController : Controller
{
public ActionResult One()
{
return View();
}
public ActionResult Two()
{
return View();
}
public ActionResult Three()
{
return View();
}
}
This is a dependency injection error.
Try this :
var WebApplication2 = angular.module('WebApplication2', ['ngRoute']);
instead of :
var WebApplication2 = angular.module('WebApplication2', ['ng-route']);
Since you are using routing, you should not declare an ng-controller attribute on your view. With routing, each of your views can use a different controller.
Instead of the HTML tag you mentioned above, it should be like this:
<html ng-app="WebApplication2">
You should declare the controller you wish to use in your route. The templateUrl is the path to the HTML file you will use as the template:
$routeProvider.when('/routeOne', {
templateUrl: 'views/route-one.html',
controller: 'LandingPageController'
})
Your controller's code should look something like this:
WebApplication2.controller('LandingPageController', function ($scope) {
$scope.models = {
helloAngular: 'I work!'
};
});
Where you are using <h1>{{models.helloAngular}}</h1> that is not in the scope of your route. The views for your routes will render in <div ng-view></div>.
In your views/route-one.html file you can add <h1>{{models.helloAngular}}</h1>.
You can view this page in the docs for an example implementation of ngRoute.
Angular is used to build single-page applications—your ASP.net's router will have nothing to do with Angular's routes. You just need to declare a single static route that is pointed to your Angular application. Server-side and client-side routing will not work hand-in-hand.

How to implement angularjs routing with cshtml

I am trying to implement angularjs routing with cshtml but i am unable to accomplish it. Can someone look into this ? what i am doing wrong.
index.cshtml:
Route 1
productmodule.js
var app = angular.module("productmodule", ["ngRoute"]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/route1', {
templateUrl: '/Product/Details',
controller: 'ProductController'
}).
otherwise({
redirectTo: '/'
});
}]);
Details.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div ng-view=""></div>
</body>
</html>
ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace webapp.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
return View();
}
public ActionResult Details()
{
return View();
}
}
}
What i wanted to achieve is when I click the Route 1 link from ( index.cshtml) I should be able to navigate to Details.cshtml
When you click your anchor tag it's going to send a request to the server (i.e. the MVC routing) for the resource at "/". Being that you didn't specify a controller or action it will look for the default, which is Home/Index (assuming you haven't changed the default route configuration). Look for code similar to the following in your .NET project.
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
);
If you want Product/Index to be the default you can change "Home" to "Product". Alternatively you can change your anchor tag to specify the controller.
Route 1
Either way, MVC will deliver the Index view and at that point Angular's routing will take over, examine the "#/route1" and load the appropriate ng-view.

mvc2 host on iis6 : The incoming request does not match any route

I have to host my project on iis6, I can not change iis setting on server.
So, I modified global.asax like below.
If I add a default.aspx and browse project I got error like : The incoming request does not match any route.
if I dont add default aspx I got HTTP Error 403.14
have any idea?
thanks
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", // Route name
"{controller}.aspx/{action}/{id}",
new { controller = "Home", action = "Index", id = "" } // Parameter defaults )
);
routes.MapRoute("Detail", // Route name
"{controller}.aspx/{action}/{id}/{sid}",
new { controller = "Home", action = "Index", id = "", sid="" } // Parameter defaults )
);
routes.MapRoute("ForGoogle", // Route name
"{controller}.aspx/{action}/{friendlyUrl}/{id}/{partialName}",
new { controller = "Home", action = "Index", friendlyUrl = "", id = "", partialName =""} // Parameter defaults )
);
routes.MapRoute(
"PostFeed",
"Feed/{type}",
new { controller = "Product", action = "PostFeed", type = "rss" }
);
}
Add an index.htm file which redirects to the right page. This has a side advantage: it does not require the webapp to be started, so it is possible to show an image or text while the webapp is started for the first time.
A fancy jquery "loading..."-page I use in some projects:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>(loading...)</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({ type: 'GET', url: 'Home.aspx', success: function() { location.href = 'Home.aspx'; } });
});
</script>
</head>
<body>
<div id="loading">
(show "loading..." text here)
</div>
</body>
</html>

Problem with Url.Content in ASP.NET MVC on Default Route

If I use the following line in my default view /Home/Index
<script language="javascript" src="<%=Url.Content("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript" ></script>
If I surf to this location using the following url http://127.0.0.1:9999/Home/Index
the page gets rendered correctly
<script language="javascript" src="/Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
If I use the following url http://127.0.0.1:9999/ (default wired to Home/Index) the page renders this:
<script language="javascript" src="//Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
Does anyone has any idea how to solve this issue?
EDIT:
FYI: I'm using ASP.NET mvc 2 RC
And this is my route configuration:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
If you use IIS6 or WinXP Cassini you should register one more route:
if (Environment.OSVersion.Version.Major < 6) // IIS6 and WinXP Cassini
{
routes.MapRoute(
"Root",
"",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
I had a very similar problem with Asp.net using Request.ApplicationPath... and wrapped it as follows
public string AppRoot()
{
var appPath = Request.ApplicationPath;
if (appPath.EndsWith("/"))
return appPath;
else
return appPath + "/";
}
Well, alternatively you can do the following:
create a key in appSettings section of web.config file.
<add key="DomainName" value="http://http://127.0.0.1:9999/" />
Now, whenever you want to assign "src" value of any image, javascript of css file, you can use this key. it will be define a root for you and after that you can define at what path you have placed your file. i.e. in your case:
<script language="javascript" src="<%=System.Configuration.ConfigurationManager.AppSettings["DomainName"] %>Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
Why are you keeping your id as an empty string? I think this may be causing the problem. You may find better results by trying the following:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
to this
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", UrlParameter.Optional } // Parameter defaults
);

Resources