Mapping route & parameters in ASP.NET MVC - asp.net

In Area VIPUsers I have controller ProfileController and other controllers.
If I want every method in ProfileController to have parameter (id)
and every method in other controllers to have parameter (userid and id)
how would I map it?
Would it be
context.MapRoute(
"ProfileMapping",
"VIPUsers/Profile/{action}/{id}",
new {controller="ManageUsers", id=""}
);
and then map a default one for all the controllers?
context.MapRoute(
"Default",
"VIPUsers/{controller}/{action}/{userId}/{id}",
new {action="Index", userId="", id = ""}
);
and...that's it? I see it's working but then it's weird...
If I go to a page on ProfileController and give it two parameters after {action} (VIPUsers/Profile/SomeAction/4/4/), it'd use the second mapped route. Is that correct?
thanks
and if I want the url to always require a UserId, how do I specify that?

The behavior you are seeing is correct. You will want to implement some route constraints to further narrow things down:
http://www.asp.net/learn/mvc/tutorial-24-cs.aspx

Related

Why are these routes being matched?

The following code:
<li>#Html.ActionLink(metaTapp.Nav_About, "Mayla", "About")</li>
<li>#Html.ActionLink(metaTapp.Nav_Support, "Support", "About")</li>
<li>#Html.ActionLink(metaTapp.Nav_Exchange, "Index", "Exchange")</li>
<li>#Html.ActionLink("Post Rfq", "Create", "Rfq")</li>
is producing the following links:
<li>About</li>
<li>Support</li>
<li>Exchange</li>
<li>Post Rfq</li>
My Global Application Start looks like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UploadRouteConfig.RegisterRoutes(RouteTable.Routes);
LocalizationConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
}
}
UploadRouteConfig.RegisterRoutes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("Upload", "Upload/Image", null).RouteHandler = new UploadMvcRouteHandler();
}
LocalizationConfig.RegisterRoutes
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Account", // Route name
"Account/{action}", // URL with parameters
new { controller = "Account", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"RfqCategory",
string.Format("{{{0}}}/Rfq/CategoryFilter/{{category}}", Constants.ROUTE_PARAMNAME_LANG),
new { controller = "Rfq", action = "CategoryFilter", category = Guid.Empty.ToString() }
);
routes.MapRoute(
Constants.ROUTE_NAME,
string.Format("{{{0}}}/{{controller}}/{{action}}/{{rfqid}}", Constants.ROUTE_PARAMNAME_LANG),
new { controller = "About", action = "Home", rfqid = "00000000-0000-0000-0000-000000000000" }
);
}
RouteConfig.RegisterRoutes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("TappDefault", "{controller}/{action}/{id}", new { controller = "About", action = "Home", id = UrlParameter.Optional }
);
I cant understand how upload is being matched to everything. If the route doesn't start with Upload/Image it should fall through to the localizationconfig routes?
Ok so the short answer to my problem is that I am rendering ActionLinks when I should be using RouteLinks. ActionLink will perform a match based on route table entries which seems like what I want but because I'm using a static Url:
"Upload/Image"
every url is matched. Why? Because routes are not filters. Routes work by matching supplied route values to the parameters of segments of the Url, but since:
"Upload/Image"
has no parameters i.e. {controller} then technically EVERYTHING is a match. RouteLink on tyhe pother hand allows me to specify which route to use when rendering the link:
#Html.RouteLink(
linkText: "route: Home",
routeName: "TappDefault",
routeValues: new {controller="About", action="Home"}
)
..
From Professional ASP.NET.MVC4 (Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen)
Page 232 Chapter 9 Routing:
Let’s suppose you add the following page route at the beginning of
your list of routes so that the URL /static/url is handled by the
page /aspx/SomePage.aspx:
routes.MapPageRoute("new", "static/url", "~/aspx/SomePage.aspx");
Note that you can’t put this route at the end of the list of routes
within the RegisterRoutes method because it would never match
incoming requests. Why wouldn’t it? Well, a request for /static/url
would be matched by the default route and never make it through
the list of routes to get to the new route. Therefore, you need to
add this route to the beginning of the list of routes before the
default route.
NOTE This problem isn’t specific to Routing with Web Forms. There are many cases where you might route to a non-ASP.NET MVC route
handler.
Moving this route to the beginning of the defined list of routes seems
like an innocent enough change, right? For incoming requests, this
route will match only requests that exactly match /static/url but will
not match any other requests. This is exactly what you want. But
what about generated URLs? If you go back and look at the result of
the two calls to Url.RouteLink, you’ll find that both URLs are broken:
/url?controller=section&action=Index&id=123
and
/static/url?controller=Home&action=Index&id=123
This goes into a subtle behavior of Routing, which is admittedly
somewhat of an edge case, but is something that people run into from
time to time.
Typically, when you generate a URL using Routing, the route values
you supply are used to “fill in” the URL parameters as discussed
earlier in this chapter.
When you have a route with the URL {controller}/{action}/{id}, you’re
expected to supply values for controller, action, and id when
generating a URL. In this case, because the new route doesn’t have
any URL parameters, it matches every URL generation attempt because
technically, “a route value is supplied for each URL parameter.” It
just so happens that there aren’t any URL parameters. That’s why all
the existing URLs are broken, because every attempt to generate a URL
now matches this new route.
This might seem like a big problem, but the fix is very simple. Use
names for all your routes and always use the route name when
generating URLs. Most of the time, letting Routing sort out which
route you want to use to generate a URL is really leaving it to
chance, which is not something that sits well with the
obsessive-compulsive control freak developer. When generating a
URL, you gener- ally know exactly which route you want to link to, so
you might as well specify it by name. If you have a need to use
non-named routes and are leaving the URL generation entirely up to
Routing, we recommend writing unit tests that verify the expected
behavior of the routes and URL generation within your application.
Specifying the name of the route not only avoids ambiguities, but it
may even eke out a bit of a per- formance improvement because the
Routing engine can go directly to the named route and attempt to use
it for URL generation.
In the previous example, where you generated two links, the following
change fixes the issue. We changed the code to use named parameters to
make it clear what the change was. #Html.RouteLink( linkText: "route:
Test", routeName: "test", routeValues: new {controller="section",
action="Index", id=123})

ASP.NET MVC 4 C# - Get Sectioned Elements or full URL to Parse

Being kind of a newb to MVC 4 (or really any of the MVC's for ASP.NET) I cant help but feel theres more to the URL helper than what I'm seeing.
Basically I've read the tutorials on populating the attributes in a controllers methods using a query string in the URL.
I dont liek query strings though and prefer a sectioned "folder" like style.
Without much further adu, this is the sample URL:
http://something.com/DataTypes/Search/searchString
this approach is actually pretty safe as there will only ever be single worded searches
I have tried in the DataTypes controller
[HttpGet]
public ActionResult Search(String q)
{
ViewBag.ProvidedQuery = q;
return View();
}
and a few other small variations, right now im just trying to get the string to show up in the view but I dont seem to be getting anything there.
Is there anyway to inject the 3rd string in the url into an attribute?
If not, which URL helper class am I supposed to use to acquire the string data in the URL? Even if I have to parse the whole URL manually so be it, i just need to acquire that 3rd element in the URL as a string
Extremely n00b question im sure, but either im not finding this simple guide somewhere, or im not searching google correctly...
What you're missing is that the default route parameter name is "id". So you want to do this:
[HttpGet]
public ActionResult Search(String id)
{
ViewBag.ProvidedQuery = id;
return View();
}
If you don't want to use the variable name id, then you can modify your Route to look like this:
routes.MapRoute(
name: "Search",
url: "DataTypes/Search/{searchString}",
defaults: new { controller = "DataTypes", action = "Search",
searchString = UrlParameter.Optional });
If you don't want the string to be optional, then you can remove the last field from the defaults object.
you can use RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)) to get the routedata
String URL to RouteValueDictionary
You need to look at the routing in the Global.asax.cs. For example for your case you could add a route to the routes collection like this:
routes.MapRoute("Search",
"DataTypes/Search/{q}",
new { controller = "DataTypes", action = "Search" }
);
Then the q parameter will automatically get mapped to your action. The default controller mapping is likely mapping it to "id".

MVC3 ActionName attribute, its behaviour and effects

While reading about mcv3 I came across an attribute name called [ActionName]. It actually gives a new name to the action method. I tested a scenario which made me think; how are the internals working. When I have the following two action methods in my controller class
[ActionName("Test")]
public ActionResult Index()
{
return View();
}
[ActionName("Index")]
public ActionResult Test()
{
return View();
}
I thought this will end up in some kind of infinite loop or will give some ambiguity exception. But the same works fine and the second method is called when i give this url http://mysite:1234/mycontroller
What made MVC engine to choose the second method and not the first?
Any idea why this happens?
Phil Haack has a post on this matter: How a method becomes an action
In short: the ControllerActionInvoker uses reflection to find a method matches the action name.
The ActionNameAttribute redefines the name of the method.
Also be aware that the name of your View matches the ActionName, not the MethodName: the method Index will search for a view with the name "Test"
This is the magic of the Routing engine. Somewhere within the global.asax.cs file there would be routing patterns defined, mostly which defaults to
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
This is a routing pattern defined for your application. The action name attribute maps to the 'action' parameter within the parameter collection (3rd parameter for MapRoute).
In your case if you map the action 'Index' to method 'Test'. It should call Test() method. I am not sure whether it is still calling Index() for you. In fact the routing engine does not care about the method name if it finds the ActionName attribute over your public method.
ActionNameAttribute it represents an attribute that is used for the name of an action. If it is not present the name of the method is used.

MVC3 how to minimize the number of controllers

i am new to MVC3 and our project needs something like:
http://www.abc.com/product_1/product_1_subpage/...
http://www.abc.com/product_2/product_2_subpage/...
right now, i have product_1 as a controller; product_1_subpage as an action of this controller, however, think about i have over 100 different products, i cannot keep create over 100 controllers for each single product, i need to do something on this structure, any idea?
thank you very much for your help, really appreciate any input.
You would probably want to have only a single Controller called Products, for all your products, instead of having to add a new controller for every product.
With custom routes, or the default routing for that matter, you would still be able to generate individual links for individual products. Also, if you were to use your approach with a new controller for every product (which you really shouldn't!), you would have to re-compile and deploy your application every time you want to add another product - which would be a pain to maintain.
It sounds like you should have a look at the tutorials about MVC provided by the .Net team to get some basic understand of MVC, and how to think about it.
Use custom routes:
routes.MapRoute(
"ProductsRoute", // Route name
"products/{productName}/{subName}/{id}", // URL with parameters
new { controller = "Product", action = "View", id = UrlParameter.Optional } // Parameter defaults
);
That would make the following work:
public class ProductController : Controller
{
// http://yourweb/products/goggles/xray/Elite2000
public ActionResult View(string productName, string subName, string id)
{
}
}
how about changing the format of the url a little to take advantage of the routing:
http://www.abc.com/product/subpage/1

ASP.MVC routes without Details action

I'd like to have URLs that are even shorter than /{Controller}/{Action}/{Id}.
For example, I'd like {Controller}/{Id}, where {Id} is a string.
This would allow for simple paths, e.g. Users/Username, Pages/Pagename, News/Newsname. I like this better than requiring the /Details action in the URL (Users/Details/Username), which is less elegant for the end-user.
I can easily make this work by setting up custom routes for any controller that I want this level of simplicity for. However, this causes headaches when it comes to implementing other actions, such as {Controller}/{Action}, where {Action} = 'Create', since, in this case the string {Action} conflicts with the string {Id}.
My question: how can I have 'reserved' words, so that if the URL is /News/Create, it is treated as an action, but if the URL is anything else, e.g. /News/A-gorilla-ate-my-thesis, then it is treated as an Id.
I'm hoping I can define this when setting up my routes?
Update:
Using Ben Griswold's answer, I have updated the default ASP.NET MVC routes to be:
routes.MapRoute(
"CreateRoute", // route name
"{controller}/Create", // url with parameters
new { action = "Create" } // parameter defaults
);
routes.MapRoute(
"DetailsRoute", // route name
"{controller}/{id}", // url with parameters
new { action = "Details" } // parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
This works a charm and means, by default, the details pages will use the simplified URL, but I will still be able to target a specific action if I want to (update/delete/details).
Of course, you will need to disallow the reserved "Create" word as an Id, otherwise a user may try to create an article, for example, with the name "Create", which can never be accessed.
This is really nice. If anyone sees that there is something wrong with this approach, chime in, but I like it so far.
I think you're left with creating a route for each reserved word. For example,
routes.MapRoute("CreateRoute",
"{controller}/Create",
new { action = "Create" }
);
would handle /News/Create, /Users/Create, etc. As long as this route is listed before your other custom route, I think you're covered.
I imagine you will need addition routes for various CRUD operations which will follow a similar pattern.

Resources