Map Routing MVC3 - asp.net

Maybe my question is very easy to respond, but I am new in MVC3.
I have these possible routes in my MVC3 Web project:
/brands/brandID
/brands/{action}/{parameters}
where brands is my controller and brandID is a specific parameter that receives my Index action. Also, my brands controller has more actions and I need to define in the Global.asax the correct map routes to make it work.

There's an example in the Custom Routing (modified for your case).
Global.asax:
routes.MapRoute(
"BrandDetails",
"Brands/{brandID}",
new { controller = "Brands", action = "Details" },
new { brandID = #"\d+" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
BrandsController:
public ActionResult Index()
{
return View();
}
public ActionResult Details(int brandID)
{
return this.View(brandID);
}

Related

How to use short urls for categories in MVC

Short urls containing product categories like
http://example.com/Computers
Should used in ASP.NET MVC 4 shopping cart.
If there is no controller, Home Index method with id parameter as Computers should called.
I tried to add id parameter to home controller using
public class HomeController : MyControllerBase
{
public ActionResult Index(string id)
{
if (!string.IsNullOrWhiteSpace(id))
{
return RedirectToAction("Browse", "Store", new
{
id = id,
});
}
return View("Index", new HomeIndexViewModel());
}
but http://example.com/Computers causes 404 error
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: /Computers
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.6.1073.0
How to force some controller call if there is no controller defined after slash in http://example.com/....
MVC default routing is used:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
It looks like MVC ignores routing parameter:
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Howe to fix this ?
your problem is because aspnet mvc is trying to find a controller with the name Computers, and your controller is Home, you can add a new route like this before the route with name Default:
routes.MapRoute(
name: "Computers",
url: "Computers",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
In the above case, you are creating a route with match with the url http://domain.com/Computers and this route will be manage by the HomeController.
Also, according to your comment, you can have a route like:
routes.MapRoute(
name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

ActionLink ignoring attribute routing settings

I have a TextObject controller, which is meant to be accessed by "~/umt/text/{action}/{id?}", as defined in the controller using attribute routing, but the action link:
#Html.ActionLink("Index", "Index", "TextObject")
ignores Attribute Routing and uses the Conventional routing definitions, producing ~/TextObject/ instead of the desired ~/umt/text/
the TextObjectController:
[Authorize]
[RouteArea("umt")]
[RoutePrefix("text")]
[Route("{action=index}/{id?}")]
public class TextObjectController : Controller
{
.....
public async Task<ActionResult> Index()
{
return View(await db.TextObjects.ToListAsync());
}
.....
}
My route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enable Attribute Routing
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Is there any additional configuration required on the controller to make the action link work or does it not work with attribute routing?
I'd like to keep it simple, and it routes correctly going directly through the url, but the ActionLink helper seems to not like something about it.
I can't see that you specify your defauld area it RouteConfig so your action link should look like:
#Html.ActionLink("TextObject", "Index", "Index", new { area = "umt" }, null)

MVC 4 Web API Areas 404 Error: "The controller for path '/Jobs/Send' was not found or does not implement IController."

I'm having an issue that is driving me nuts.
I have an MVC 4 WebAPI application that has several Areas defined.
My Jobs Area Send controller (SendController.cs) is defined like so:
namespace TargetAPI.Areas.Jobs.Controllers
{
public class SendController : ApiController
{
[HttpPost]
public HttpResponseMessage Index(SendRequest req)
{
try
{
//blah blah
}
catch (Exception ex)
{
//blah blah
}
}
}
}
My Jobs Area Registration (JobsAreaRegistration.cs) is defined like so:
namespace TargetAPI.Areas.Jobs
{
public class JobsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Jobs";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Jobs_long",
"Jobs/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "TargetAPI.Areas.Jobs.Controllers" }
);
}
}
}
My RouteConfig.cs says:
namespace TargetAPI
{
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 string[] { "TargetAPI.Controllers" }
);
}
}
}
When I run the route debugger on it I get:
(source: boomerang.com)
But when I try to post to the URL "Jobs/Send" I get:
The controller for path '/Jobs/Send' was not found or does not implement IController.
I've tried so many iterations and combinations my head is spinning. Any ideas?
Thanks!
Turns out the WebAPI does NOT handles Areas! Imagine my surprise. So I found a GREAT post http://blogs.infosupport.com/asp-net-mvc-4-rc-getting-webapi-and-areas-to-play-nicely/. Now I am moving forward.
In addition to not supporting Areas (because MapHTTPRoute doesn't have namespace support), The API controller must use MapHttpRoute, not MapRoute as in this example (after removing area):
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Note the absence of {action}, the Method's are not Actions, put are taken from the HTTP request: Get, Head, etc...
I had the same problem, the solution was simple: I forgot to add files _ViewStart.cshtml and _Layout.cshtml, and can help you

ASP.NET MVC 2 route not resolving properly (or, rather, how I think it should)

I've never come across the need to attempt the following such routes, where a user can visit another's home page, or their own (admin) home page. Here are the routes I have:
routes.MapRoute(null, "Home/Me",
new { controller = "Home", action = "Admin" });
routes.MapRoute(null, "Home/{userID}",
new { controller = "Home", action = "Visitor" });
Apparently I've incorrectly assumed that "Home/6e982cc5-4d1d-4232-947b-835e54e49c7" will resolve to the following action on the Home controller:
public ActionResult Visitor(Guid userID) {}
Would anyone be kind enough to explain why this doesn't work like I think it should?
Assuming the following routes setup:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
null,
"Home/Me",
new { controller = "Home", action = "Admin" }
);
routes.MapRoute(
null,
"Home/{userID}",
new { controller = "Home", action = "Visitor" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Home/4 will resolve to the Visitor action of the Home controller but the default model binder will throw an exception because 4 is not a valid value for a Guid.
On the other hand Home/6e982cc5-4d1d-4232-947b-835e54e49c7 should work. Home/Me will resolve to the Admin action on the Home controller.

ASP.NET MVC - Routes

I'm working on an MVC application and I have and admin area... So what I need is:
When user makes request to admin (for example "/Admin/Post/Add") I need to map this to controller AdminPost and action Add... is it possible?
If your controller is named AdminPostController and you want it to map to '/Admin/Post/Add' then you can use:
routes.MapRoute("Admin", // Route name
"Admin/Post/{action}/{id}", // URL with parameters
new { controller = "AdminPost", action = "Add", id = "" } // Parameter defaults
);
Note the use of the parameter defaults.
If your controller is named AdminController and you just wanted to separate the request method then use the default:
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Which will map '/Admin/Add/' to the controller:
public class AdminController : Controller {
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(int id) {
//...
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Add(int id) {
//...
}
}
Note the use of [AcceptVerbs] to identify which method to invoke for POST requests and GET requests.
See Scott Gu's blog for more details

Resources