Managing routing for mobile and web browsers - asp.net-mvc

We are trying to create two views for our MVC app. Mobile and Web
These were the two links we followed
Handling routing for both Desktop & Mobile Controllers in one instance of ASP.NET MVC
Mixing ASP.NET MVC Display Mode Providers and Routing Rules
Created Account/Login.cshtml page and Account/Login.Mobile.cshtml page (with different layouts). Created a default route
routes.MapRoute(
name: "DefaultMobile",
url: "mobile/{controller}/{action}/{id}",
defaults: new
{
mobile = true,
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
But the problem is that we are using routes.MapMvcAttributeRoutes(); and generating urls like \login. Is there a way to force mobile/login to fetch mobile view. something that force the Routing to display mobile view if the url starts with '/mobile/'?
Or is there another way to do it?

You should be able to specify 2 route definitions with attribute routing as well, one for normal login and one for mobile
[Route("{type}/Login")]
[Route("Login")]
public ActionResult Login(string type = "")
{
var isMobile = String.Equals(type,"mobile",StringComparison.OrdinalIgnoreCase);
// to do : Return something
}

Related

Hide url Controller and Action - Asp.NET MVC5

I would like to keep the same server url. ex: 10.139.183.192 to all pages.
I don't want to show 10.139.183.192/Task/Create
The route must continues, when the user type on address bar. But I want to hide it.
I've been searching a lot about url rewrite, but I can't find a solution.
I've tried to change the Global asax, Register Routes, etc.
Shoud I change in the IIS Server or in the Application?
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 }
);
}
You can work all pages on Home Controller and return View depending the post, exemple:
public ActionResult Home()
{
string page = Request["page"];
switch (page)
{
case "Home":
return View();
break;
case "Product":
return View("Product");
break;
default:
return View();
break;
}
return View();
}
or
User accesses all controllers and you code JS to change URL, like this:
window.onload = function(){
window.history.pushState("", "", "/");
}
You can only do that natively if you use a client side framework such a Angular.JS.
In C#.NET MVC5 only three ideas come to my mind.
Use AJAX to change the content of the page without going to an other page
Second, you use a home-made routing like #Rodolfo said
Third and last (this is the weirdest one), you call your pages not in GET but passing POST data (making a FORM for each link) so the base route can control the displayed content based on the form data. This allows you to always target the same URL 10.139.183.192, unlike the point just above where the URL would change (GET parameters).
Personally, I think that what you are trying to achieve should be done either with a dedicated client side frameworks (they were made for that, but it would be JavaScript, not C# I believe) or using the Ajax method.

How to use ASP.NET MVC and AngularJS routing?

I’m working on a new ASP.NET MVC and AngularJS application that is intended to be a collection of SPAs. I’m using the MVC areas concept to separate each individual SPA, and then I’m using AngularJS within each MVC area to create the SPA.
Since I’m new to AngularJS and haven’t been able to find an answer regarding combining both MVC and AngularJS routing, I thought I’d post my question here to see if I could get some help.
I have the standard MVC routing setup, which serves up each MVC area.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.AppendTrailingSlash = true;
}
This works fine and gives me URLs like:
http://servername/Application1/
http://servername/Application2/
Now, within each application area, I’m trying to use AngularJS routing, also using $locationProvider.html5Mode(true); so that I get the client-side routing within each area, something like:
http://servername/Application1/view1
http://servername/Application1/view2
http://servername/Application2/view1/view1a
http://servername/Application2/view2/view2a
http://servername/Application2/view3
Here’s my AngularJS routing snippet for Application1:
app1.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
var viewBase = '/Areas/Application1/app/views/';
$routeProvider
.when('/Application1/view1', {
controller: 'View1Controller',
templateUrl: viewBase + 'view1.html'
})
.when('/Application2/view2', {
controller: 'View2Controller',
templateUrl: viewBase + 'view2.html'
})
.otherwise({ redirectTo: '/Application1/view1' });
$locationProvider.html5Mode(true);
}]);
So, initially, it seems to work (at least the URL looks correct). But, when I start navigating between areas or views within an area, or even if I refresh, something gets “lost” and things don’t work. The URL still looks correct but views aren’t found and aren’t getting loaded correctly.
Any help/guidance on how to make ASP.NET MVC and AngularJS routing work together to give me the scenario described above?
Thanks!!!
Thanks for the answer, agbenyezi. I looked at the article you provided but it only got me back to where I was anyway.
However, I was able to figure it out and get it working. The answer turned out to be relatively simple, but it took some time and a lot of searching around. Anyway, since I am using MVC areas, navigating to a URL of http://servername/Application1/view[x] (where Application1 is the MVC controller (in the area) and view1, view2, view3, etc. are Angularjs views), the MVC part of the overall application was getting confused and trying to find an action named view[x] in the Application1 controller (which doesn't exist).
So, in the area's AreaRegistration class (where it's defining specific routes for the area), I just needed to add a kind of catch-all route before any default MVC routes to always force it to the Index action on the Application controller. Something like:
// Route override to work with Angularjs and HTML5 routing
context.MapRoute(
name: "Application1Override",
url: "Application1/{*.}",
defaults: new { controller = "Application1", action = "Index" }
);
Now, when I navigate to http://servername/Application1/view[x] it routes to the Application1 MVC controller, Index action, and then Angularjs takes over routes to the different views, all while having the HTML5 routing construct in the URL.

AngularJS app with ASP MVC - getting rid of hasbang with URL rewrite/routes

I have kind of a mixed application with Angular and ASP.NET MVC.
It works this way:
User enters example.com, MVC controller checks if he is Authorized:
if he is, controller returns view Main which contains Angular app.
if he isn't, then a view Index is shown, with login/register form
Logging in/ registering is done within Account controller at example.com/Account
Angular app has html5Mode enabled, so inside-app routing is like example.com/home,example.com/profile etc.
I've tried messing aroung with MVC's RouteConfig, as well as simple rewriting
protected void Application_BeginRequest( Object sender, EventArgs e )
{
string url = Request.Url.LocalPath;
if ( !System.IO.File.Exists( Context.Server.MapPath( url ) ) )
Context.RewritePath( ROOT_DOCUMENT );
}
source: ui-router GitHub page
But nothing adresses my situtation.
Above code basically disables whole MVC routing, so I can't access /Account/LogIn
I've faced a similar issue. I think the best answer I can come up with is to define specialized routes that will allow access to the controllers, and then define a DefaultAll route that will default to the specific controller, and action method that has my Angular code.
For example in my case I have one controller Page, and my first route is
routes.MapRoute(
name: "Default",
url: "Page/{action}/{id}",
defaults: new { controller = "Page", action = "Main", id = UrlParameter.Optional }
);
This means any request with Page/ - will route appropriately to the controller, and use the action method defined in the request. For example Page/main, Page/one, Page/two
My second request is a catch all that defaults to the controller Page, action method Main.
routes.MapRoute(
name: "DefaultAll",
url: "{*.}",
defaults: new { controller = "Page", action = "Main", id = UrlParameter.Optional }
);
This means when I paste a url like http://localhost/myapp/persons , it will load the Page controller, Main action method, which has my Angular routes defined and then Angular will parse the persons part of the URL to perform its routing.
This does mean that if you have more controller, you will need a specialized route for each one.
If you have come up with a better way please do let me know.

How can I set the default page in IIS to a Controller?

We have an MVC application that is accessed from two separate websites. The default website is fine, however how can I setup the second site to startup in a specific Controller?
Our default site is www.mysite.com, and we'd like to add a second IIS site for the header www.subdomain.mysite.com that should take users to www.subdomain.mysite.com/controller
But how can I tell IIS to startup www.mysubdomain.mysite.com with the specific controller action mycontroller?
I would consider configuring URL Rewrite so that requests to www.mysubdomain.mysite.com get seen as requests to www.mysubdomain.mysite.com/controller.
You could use Ionics Isapi Rewrite Filter.
Ionic's Isapi Rewrite Filter, aka IIRF, is a small, FREE, easy to use,
URL rewriting ISAPI filter. It combines a good price (free!) with good
features. It is fast and powerful. It works on IIS 6.0, and later.
I ended up adding a value to my AppSettings in web.config, and adjusting the default route of the application based on that value.
public static void RegisterRoutes(RouteCollection routes)
{
var defaultController = ConfigurationManager.AppSettings["DefaultController"];
if (string.IsNullOrEmpty(defaultController))
defaultController = "Home";
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = defaultController, action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
...
}
This allows me to host any number of IIS sites that can each start with a different controller in the application.

ASP.NET MVC App Routing Not Working For Dynamic Data WebForm Pages

I need the correct Global.asax settings in order for my Dynamic Data site to run under an ASP.NET MVC project. The routing currently appears to be my issue.
Here is my global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
MetaModel model = new MetaModel();
model.RegisterContext(typeof(Models.DBDataContext), new ContextConfiguration() { ScaffoldAllTables = true });
routes.Add(new DynamicDataRoute("DD/{table}/{action}.aspx") {
Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
Model = model
});
routes.MapRoute(
"Assignment",
"Assignment/{action}/{page}",
new { controller = "Assignment", action = "Index", page = "" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Admin", action = "Index", id = "" }); // Parameter defaults
}
Link that I'm trying to use is:
http://localhost:64205/DD/Work_Phases/ListDetails.aspx
I am getting the following message:
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 is temporarily
unavailable. Please review the
following URL and make sure that it is
spelled correctly.
Requested URL:
/DD/Work_Phases/ListDetails.aspx
I've tried replacing DD with DynamicData since the folder inside of the app is DynamicData and that yielded the exact same result.
The URL
http://localhost:64205/DD/Work_Phases/ListDetails.aspx
is matching your second (default) route, which is trying to hit a controller called "DD".
You may need another route entry that looks something like this:
routes.MapRoute(
"DD",
"DD/{action}/{page}",
new { controller = "NameOfController", action = "Index", page = "" }
);
...although I can't imagine why you would need to pass a page parameter. The page view that is hit depends on the return action of the controller method.
For a better look at integrating Dynamic Data with ASP.NET MVC, have a look at Scott Hanselman's Plugin-Hybrids article. He has some details about handling the .ASPX files that are not part of MVC. In particular, if you have an .ASPX that you don't want to be processed by the ASP.NET MVC controllers, you can install an Ignore Route:
routes.IgnoreRoute("{myWebForms}.aspx/{*pathInfo}");
It should be noted that ASP.NET MVC is configured out of the box to ignore URL requests for files that physically exist on the disk, although Scott's IgnoreRoute technique is apparently more efficient.
The url doesn't match your dynamic data route because it doesn't fit the constraints you put on it. You're requesting action ListDetails but only these actions are allowed
Constraints = new RouteValueDictionary(
new { action = "List|Details|Edit|Insert" }
EDIT: are you sure that an action called ListDetails exists? Then modify the constraints above to
Constraints = new RouteValueDictionary(
new { action = "ListDetails|List|Details|Edit|Insert" }
Just to be sure that it's the constraints that's causing the route to be ignored, can you try one of the default actions? E.g.
http://localhost:64205/DD/Work_Phases/List.aspx
For ASP.NET MVC to work, you will have to match the URL you are trying to access with the list of routes.
For your current global.asax, example of valid URLs are:
http://domain/AnyController/AnyAction/AnyParameter
http://domain/Assignment/
http://domain/Assignment/AnyAction/AnyParameter
MVC requests are redirected to the proper Controller class, Action method, with parameters as passed in. MVC request is not redirected to any ASPX class. This is the difference between ASP.NET MVC and vanilla ASP.NET Page.

Resources