ASP.NET MVC routing without unnecessary text - c#

I have a problem with my MVC. Think like a URL.
domain.com/product/any-product/1
domain.com/category/any-category/1
Can I change url like this?:
domain.com/any-product/1
domain.com/any-category/1
Also can I delete id?
context.MapRoute(
name: "category",
url: "category/{category_name}/{category_id}",
defaults: new
{
controller = "Cateogory",
action = "Index",
Area = "Shop"
}
);
context.MapRoute(
name: "product_detail",
url: "product/{category}/{product_name}/{product_id}",
defaults: new
{
controller = "Product",
action = "ProductDetail",
Area = "Shop",
product_name = UrlParameter.Optional,
product_id = UrlParameter.Optional
}
);

No, you can't do it exactly like that, but you can get closer. Think for a second about what you're saying you want:
/any-product/ => ProductController
/any-category/ => CategoryController
Now, logically speaking, how is MVC supposed to sort out which URL is referring to a product and which is referring to a category?
You could do something like:
/any-category/ => CategoryController
/any-category/any-product/ = > ProductController
Now, there's some way to for MVC to work out that the URLs are different. If there's something after the category part of the path, then it's a product.
As for removing the id portion, that depends. The point of the id in the first place is that you need some sort of unique identifier for a record that should be loaded. If "any-product" is a string that can uniquely identify the record (you have column in the database with that value and there's only one with that value), then you can use that string to look up the entity instead. Then, no, you no longer need the id portion of the URL. However, if the string is not unique or doesn't correspond to data in the database, then you need the id to locate the record, and it cannot be removed.

Related

Basic Conventional routing asp.net webapi

I have a simple query on ASP.Net Web API Routing. I have the following controller:
public class CustomersController: ApiController
{
public List<SomeClass> Get(string searchTerm)
{
if(String.IsNullOrEmpty(searchTerm))
{
//return complete List
}
else
{
//return list.where (Customer name contains searchTerm)
}
}
}
My routing configuration (Conventional) looks like this:
config.Routes.MapHttpRoute(name:"DefaultApi",
routeTemplate:"api/{controller}/{id}"
defaults:new {id = RouteParameter.Optional});
config.Routes.MapHttpRoute(name:"CustomersApi",
routeTemplate:"api/{controller}/{searchTerm}"
defaults:new {searchTerm = RouteParameter.Optional});
If I hit the url:
http://localhost:57169/api/Customers/Vi
I get a 404-Not found
If I reverse the order of the routes, it works.
So the question is in the first case, is it matching the first route (DefaultApi)? If not, why is it not trying the second route?
This route template
config.Routes.MapHttpRoute(name:"DefaultApi",
routeTemplate:"api/{controller}/{id}",
defaults:new {id = RouteParameter.Optional}
);
match your URL because Id can be any type : string, int etc. So your URL respect this template and this route is chosen.
To make this template more restrcitive and make ASP.Net Web API to go to the next template you need to add to it some constraints by saying something like "Id parameter must be a numeric type for this template". So you add constraints parameter like below:
config.Routes.MapHttpRoute(name:"DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Required}, // <- also here I put Required to make sure that when your user doesn't give searchTerm so this template will not be chosen.
constraints: new {id = #"\d+"} // <- regular expression is used to say that id must be numeric value for this template.
);
So by using this URL http://localhost:57169/api/Customers/Vi the above template will be skipped and the next will be chosen.

Url.Action generates a wrong url

I use the Url.Action method to generate a Url string.
Thats the result:
"/Home/GetRejectTest/0?IsSelected=False"
The controller and action name are correct but the query parameters are screwed up. Is this because The action does not have a RouteAttribute thus query parameters are generated?
My action:
public ActionResult GetRejectTest(Test test)
{
return new EmptyResult();
}
Test class has those 3 properties Id, Name, IsSelected.
My route definition:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The url your generating (/Home/GetRejectTest/0?IsSelected=False) is correct for your route definition. You passing a new instance of Test to the Url.Action() method, which
Internally builds a dictionary based on the name and value
(using.ToString()) of each property in your model - i.e.
controller=Home, action=GetRejectTest, id=0, Name=null, IsSelected=False
Then searches your route definitions for a match which it finds
(url: "{controller}/{action}/{id}") and updates the placeholders
(which at this point generates /Home/GetRejectTest/0) but your
route definition does not have url parameters for Name and
IsSelected so these are added as query string parameters (because
Name is null, a query string for that propery is not generated)
so the result is now /Home/GetRejectTest/0?IsSelected=False
You have not indicated what result you're actually expecting, but creating specific route definitions will solve most cases. For example if you want
/Home/GetRejectTest/0/false
or /Home/GetRejectTest/0/false/someName if the value of Name is not null, then you can create an additional route (which must be before the default route)
routes.MapRoute(
name: "Test",
url: "Home/GetRejectTest/{id}/{isselected}/{name}",
defaults: new { controller = "Home", action = "GetRejectTest", name = UrlParameter.Optional }
);
Note that because Name is typeof string and therefore can be null, the {name} placeholder needs be the last one and marked as UrlParameter.Optional (otherwise it will revert back to using query string parameters)

Can't get multiple parameters to controller to work

Here's the jquery from my view:
$("#btnSelect1").click(function () {
var donationTypeID = $(this).closest('p').find('#selectList').val();
var id = parseInt(donationTypeID);
var id2 = $('#person').val();
var persId = parseInt(id2);
// var personName
var route = '/Donation/ContinueDonation/' + id + '?personId =' + persId;
$("#donationSection1").load(route, function () {...});...
Here's the controller method
public ActionResult ContinueDonation(int id, int personId)
{}
Any thoughts on how I can get this to work? Thanks
I actually think the previous answer is not all that right. Your query string is correct if it were hitting the default route established by MVC which matches a URL something like this {controller}/{action}/{id}.
What must really be going on is that you messed with the routes and your query is either not hitting the default route or you changed that.
What I would do is get the RouteDebugger (just get it via nuget) and see which route your query string hits. You could setup a route for any URL you want it to be (sort of the whole point of friendly URLs), so If you want the route to be /ContinueGiving/{id}/{personId} you can do that by adding a route to the beginning of the routes getting added with a definition something like this:
routes.MapRoute(
name: "ContinueDonation",
url: "ContinueGiving/{id}/{personId}",
defaults: new { controller = "Donation", action = "ContinueDonation" },
constraints: new { id = #"\d+", personId = #"\d+" }
);
Any parameters you do not specify will get mapped if the framework can find any matching items in either posted values, the query string, etc.
The constraints make sure this route only gets matched if the parameters passed are numbers.
So the previous answer worked because somehow the route with id didn't match, but that is not really your issue.
You didn't give a key to the id value:
var route = '/Donation/ContinueDonation/?id=' + id + '&personId =' + persId;
BTW, the var persId = parseInt(id2); line is redundant, as every parameter sent with HTTP is a string, so "234" and 234 are exactly the same.

MVC ActionLink generating different types of links... why?

I'm new to MVC land, and have an app that i'm working on. i have 2 different links with 2 routes in my global which are fairly similiar
route 1
routes.MapRoute("Category", "Movies/{category}/{subcategory}",
new { controller = "Catalog", action = "Index", category = "", subcategory = "" });
route 2
routes.MapRoute("Movie", "Movie/{movie}",
new { controller = "Movie", action = "Index", movie = "" });
When i call an actionlink for the first route it creates it as i would think it should:
.../Movies/Category/SubCategory
however when i create my second link it populates it like this:
.../Movie?movieId=ff569575-08ec-4049-93e2-901e7b0cb96a
I was using a string instead of a guid before and it was still doing the same i.e.
.../Movie?movieName=Snatch
my actionlinks are set up as follows
<%= Html.ActionLink(parent.Name, "Index", "Catalog",
new { category = parent.Name, subCategory = "" }, null)%>
<%= Html.ActionLink(movie.Name, "Index", "Movie",
new { movieId = movie.MovieId }, null)%>
My app still works, but i thought this behavior was strange. any help would be great.
Thanks!
routes.MapRoute("Movie", "Movie/{movieId}",
new { controller = "Movie", action = "Index", movie = "" });
Should the route text not match the name of the property which you are submitting to the mvc link?
The problem is that when you call ActionLink, the routing system can't figure out which of the two routes to use, so it chooses the first. The solution is to use RouteLink instead of ActionLink. RouteLink lets you specify the name of the route to use when generating the URI. Then there is no ambiguity as to which route to use. I think that ActionLink is obsolete. I can think of no reason to use it in lieu of of RouteLink.
However, you may still have a problem when the user submits links. In that case, use route constraints to enforce the selection of the correct route.
Andrew is correct (up-voted) that the tokens you use in ActionLink/RouteLink and the route itself must match.

Why the query strings in my ASP.NET MVC route?

On an ASP.NET MVC (Beta) site that I am developing sometimes calls to ActionLink will return to me URLs containing querying strings. I have isolated the circumstances that produce this behavior, but I still do not understand why, instead of producing a clean URL, it decides to using a query string parameter. I know that functionally they are the same, but for consistency (and appearance) of the URLs this is not what I want.
Here are my routes:
routes.MapRoute(
"Photo Gallery Shortcut",
"group/{groupname}",
new { controller = "Photos", action = "All", Id = "" });
routes.MapRoute(
"Tagged Photos", //since the Tagged action takes an extra parameter, put it first
"group/{groupname}/Photos/Tagged/{tagname}/{sortby}",
new { controller = "Photos", action = "Tagged", Id = "", SortBy = "" });
routes.MapRoute(
"Photo Gallery", //since the Gallery's defualt action is "All" not "Index" its listed seperatly
"group/{groupname}/Photos/{action}/{sortby}",
new { controller = "Photos", action = "All", Id = "", SortBy = "" });
routes.MapRoute(
"Group", //<-- "Group" Category defined above
"group/{groupname}/{controller}/{action}/{id}",
new {controller = "Photos", action = "Index", Id = ""});
Now the problem only occurs when I am looking at the view described by the route named "Tagged Photos" and execute ActionLink via:
Html.ActionLink<PhotosController>(p => p.All((string)ViewData["group"], ""), "Home")
Which produces the URL:
http://domain/group/GROUPNAME?sortBy=
From any other view the URL produced is:
http://domain/group/GROUPNAME
I have pulled down Phil's ASP.NET Routing Debugger, and everything appears in order. This one has me stumped. Any ideas?
Not sure why different views are producing different URLs.
But you can get rid of that sortBy param by assigning a default value to the first route.
new { sortBy = "" }
During generation, if sortBy matches the default, the route engine will skip that parameter (if it's in the query string).
You're going to have to use named routes here, not action routes, because of the way routing works in ASP.NET, because it does "first match", not "best match".
I think it is picking up your first Route. It too has the action All. And because the sortby is not specified it is exposing it as a querystring parameter
This will still work with the action method 'All' on the PhotosController, because it just fills the sortby parameter with the query string value.
In the Route Debugger is it executing the 3rd route or the 1st?

Categories