ASP.NET MVC website route map not working - model-view-controller

In my ASP.NET MVC website, I want to route
p/this-is-some-dynamic-text-and-delimited-by-hyphen/2086
to
myarea/profile/detail/2086
Basically, I want to use the letter p and the id number to display the profile, so i will ignore the area and whatever text in between p and id.
I have an Area called 'Myarea', and the controller is: Profile, action is Detail.
How do I setup the route map? here is what I tried, but not working:
routes.MapRoute(
name: "Pa Profile",
url: "p/{text}/{id}",
defaults: new { controller = "Profile", action = "Detail", id = UrlParameter.Optional }
);

I figured this out by moving the maproute code to area register function:
public override void RegisterArea(AreaRegistrationContext context) {}

Related

First time with MVC

Im new to MVC and I would like to ask about routing and controllers.
I have a controller called an LprController
public ActionResult Index()
{
return View();
}
and I have a view called ScanPage
#model FCoai.FCWCF.PCSResult
#{
ViewBag.Title = "ScanPage";
}
<h2>ScanPage</h2>
and here's my routeconfig
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I'm trying to directly display the scanpage screen instead of the regular MVC about page but I'm having no success. I'm using a service reference that's why I have no model class, please give me some tips on how to do response.redirects like how I'm used to doing with regular asp web programming.
To display the scan page as a default page in your web app, you need to do three things:
Add the following action to your controller "it should match the view name":
public ActionResult ScanPage()
{
return View();
}
Make sure your scanpage.chtml is placed in the following path "views/Lpr/scanpage.cshtml". Note that Lpr in the path is the name of your controller "without the Controller suffix".
Make your page the default page in the following routing line:
So, you need to change this:
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
into this:
defaults: new { controller = "Lpr", action = "ScanPage", id = UrlParameter.Optional}
That's it. Hoping this would help you.

MVC 4 URL rewrite

I don't find how I can create a "fake" subfolder in MVC4.
I want that an URL like
AREA/CONTROLLERNAME/FAKEFOLDER/ACTION/
goes to
AREA/CONTROLLERNAME/ACTION
Is it possibile? Any suggestions?
Thanks!
Have you tried using routing? For example assuming you have an Admin area:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/FAKEFOLDER/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
Now when you request /admin/home/fakefolder/index the Index action of HomeController within the Admin are will be executed.
You could add a MapRoute that expects an extra parameter in your route (fakefolder in the example below). Then, the routing occurs as usual, where the controller's action serves the page. Example:
routes.MapRoute(
name: "FakeFolder",
url: "{controller}/{fakefolder}/{action}",
defaults: new { controller = "home", action = "index", fakefolder = UrlParameter.Optional}
);
Notice that with this routing you can use any "folder name" since it is just a placeholder.
Url example:
myController/SomeFakeFolder/someAction will execute the action someAction in myController

MVC3 Routing with Areas

I have a MVC3 application with two areas and a root area. The general structure looks like
Root
- Root/Areas/Manager
* Views/Home/Index.cshtml
* ManagerAreaRegistration.cs
- Root/Areas/Participant
* Views/Home/Index.cshtml
* ParticipantAreaRegistraion.cs
- Root
* Views/Home/Index.cshtml
* Views/Account/Register.cshtml
* Global.asax.cs
I am having two problems with routing. The first is that I am unable to navigate to any pages in the Root/Views folders except the one set as default in the Global.asax.cs file. The Global.asax.cs file looks like:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {controller="Home" , action = "Index", id = UrlParameter.Optional },
new[] { "MVCApplication.Controllers" } // for areas
);
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
...
And the code in Root/Views/Home/Index.cshtml which is the start page looks like:
#Html.ActionLink("Accounts","Register", new {area="", controller="Accounts"},null)
#Html.ActionLink("Manager", "Index", new { area = "Manager", controller = "Home" })
#Html.ActionLink("Participant", "Index", new { area = "Participant", controller = "Home" })
The two area links work fine as I have added routes into the registration files in each area, but the link to Accounts/Register which is another page in the root gives a 'resources not found error'. However, if I change the Global.asax.cs route to have
new {controller="Accounts" , action = "Register", id = UrlParameter.Optional },
in the default route, then I can start on the Register page.
So my first question is: How do I use routes to be able to access both pages in the Areas and in the Root (ie the Accounts/Register page)?
My second question has to do with the areas themselves. Since they both have a 'Home' controller, I have put the area name in front of one to distinguish it, but I would like to not have to do this. Currently the 'ParticipantAreaRegistration.cs file has the code:
context.MapRoute(
"Participant_default",
"Participant/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "MvcApplication.Areas.Participant.Controllers" } // for areas
);
which gives URL's of "localhost**/Participant/Home"
while the ManagerAreaRegistraion.cs has code
context.MapRoute(
"Manager_default",
"{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "MvcApplication.Areas.Manager.Controllers" } // for areas
);
which gives URL's of "localhost***/Home/"
My second question is : How can I have the URL of "localhost**/Home for both Manager and Participant (or for any number of areas) without having to have the Area name displayed in the URL?
I know this question is similar to others already on file, but I have scoured these to no avail and am currently drowning in inefficiency, so I thought I would try asking with specificity. Thanks.
You can use custom routing.
Something similar to this one:
MVC 2 AreaRegistration Routes Order
Using the solution in the above problem, you can write custom order of routing.
In one of my application, I have areas named Admin,Blog,Members and
Public. I have routed the Public area as the url:
http://localhost:4000/, Admin as: http://localhost:4000/admin, blog
as: http://localhost:4000/blog, etc.. If you want my code, I can give
you.

Area can't load in MVC - the resource cannot be found

I have a problem. I have a area in MVC 3 called Page that works as it should.
I just added a new Area called Media and now I get "the resource cannot be found" for that new area. I am going crazy, since it looks exactly like the PageArea that works.
Here is the MediaAreaRegistration.cs
public override string AreaName
{
get
{
return "Media";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Media_default",
"{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
Here is my global.asax
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
I am trying to access via localhost/media/, but I am just getting "the resource cannot be found".
Any ideas?
Check the Namespace of the Controller;
In my case; the default route was:
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", AreaName="Admin", id = UrlParameter.Optional },
namespaces: new[] { "MyApp.Admin.Controllers"}
);
But when I was create the controller, the MVC automatically set "MyApp.WebUI.Areas.Admin.Controllers" as the namespace of the new Controller; I Changed the namespace to what I defined in default route as "MyApp.Admin.Controllers" and application works fine.
Typically, when you create an area, you will get a somewhat different default route than what is in global.asax. For example, I created a Media area in an MVC3 project, and the default route looks like this:
context.MapRoute(
"Media_default",
"Media/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
Routes in areas are really no different than routes defined in your global asax, except that they look for controllers in a different namespace. Also, they are loaded before the routes in your global.asax. You can see this because in Application_Start, RegisterAllAreas is invoked before RegisterRoutes.
Typically, this is the URL schema for root controllers with routes defined in your global.asax:
base/ControllerAName/Action1Name
base/ControllerAName/Action2Name
base/ControllerBName/Action6Name
...and so on. This is the "convention" you get with MVC out of the box. Look closely, and you will see that this pattern matches the base route definition in your global asax:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
On the other hand, the convention when you use areas is that your "conventional" URL schema will look like this:
base/AreaName/ControllerAName/Action1Name
base/AreaName/ControllerAName/Action2Name
base/AreaName/ControllerBName/Action6Name
Notice the difference? This is why your default route definition in the area registration looks like this: "Media/{controller}/{action}/{id}"
With all of this said, there is nothing stopping you from deviating from the conventions. It sounds like you want to have an area named Media, and a URL base/media that goes to some action method on some controller in the area. If that is correct, try this -- remembering to put your more specific route before the default route generated by MVC:
context.MapRoute(null,
"media",
new { action = "Index", controller = "Media" }
);
context.MapRoute(
"Media_default",
"Media/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
This means that MVC will match base/media to the Index action method on the MediaController in your Media area, since that route is defined first.
Also, when you create a new area, don't change any namespaces. This will only cause you problems.
Another tip is to not give route names to your routes. Notice how I passed null as the first argument. This is considered good practice -- accessing routes by name can get very messy.
I suggest you try starting a new project, or creating a new area, and trying these suggestions. Grasping routes coming from webforms can be tricky, but once you get a handle on it, I think you will find it superior to the URL-TO-FILE mapping in webforms.
In my case, someone added routes.Clear() in RouteConfig.cs, before any area ever existed. But now I added an area, this was erasing all its routes.

Make three-part route url for controller in ASP.NET MVC3

I am using ASP.NET MVC3 and curious about how to make routes like /Account/Ajax/Action map to controller AccountAjaxController method Action
Is there any way to do so?
Already solved issue using following code in Global.asax.cs file:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional},
new[] {"MyProjectName.FrontEnd.Web.Logic.Controllers"}
);
routes.MapRoute(
"Ajax",
"Ajax/{controller}/{action}/{id}",
new[] {"MyProjectName.FrontEnd.Web.Logic.Controllers.Ajax"}
);
One way that I've done this is with RouteCollection.MapRoute(). See http://msdn.microsoft.com/en-us/library/dd470521.aspx. You can do all kinds of stuff with routes.
In the code below I would typically call this from my global.asax.cs Application_Start():
RouteCollection routes = RouteTable.Routes;
routes.MapRoute(
"ArbitraryRouteName", // Route name
"Account/Ajax/Action/", // URL with parameters
new
{
controller = "AccountAjax",
action = "Action"
}, // Parameter defaults
new
{
}
);
There are many ways to use this in order to generate links. You can use Html.RouteLink() in your views as an example. I believe that you can also call Html.ActionLink("link text", "AccountAjax", "Action"). I think that providing there is only one Route mapped to your controller and action name, ASP.NET MVC automatically figures out the proper URL to generate from your route mappings.
See http://msdn.microsoft.com/en-us/library/dd492585.aspx for an example of the RouteLink extension method.

Resources