Add Extra parameter with url in mvc3 - asp.net-mvc

i am new in asp.net mvc3. i want to add extra parameter with url before controller like:-
Newparameter/{controller}/{action}/{id};
is it posible and also i need to change its value.
Please Help....

Yes it's possible, just add a new route in your Global.asax like this:
routes.MapRoute(
"Default with new param", // Route name
"{newParameter}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Place this before the default route as it's more specific.
Then create an action method that takes 'newParameter' as a method parameter

you will have to define a new route in Global.ascx like
routes.MapRoute(
"RouteName",
"{Param}/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
and dont forget to place your new route above the default route

Related

How to map same routes for two controller?

I have two controller in my MVC application. One is Home controller and other is User controller. I am using following RouteConfig settings.
routes.MapRoute(
"actiononly",
"{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I want abc.com/Blog
abc.com/Login
Instead of abc.com/Home/Blog
abc.com/User/Login.
Above configuration works fine with abc.com/Blog but it is not working with abc.com/Login.
How to remove controller name from the link for both controllers?
Also how can I only show abc.com when website launches instead of abc.com/index? I am using following code in my webpage to access the particular page.
#Html.ActionLink("Home", "Blog", "Home")
#Html.ActionLink("Login", "Login", "User")
Your default route should automatically cater for wanting to nav to abc.com without requiring the index part of the URL
You need to ensure that your main route is specified as the default:
context.MapRoute(
"Site_Default",
"{controller}/{action}/{*id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
If you want to map short routes you can do exactly what you've done above. I use this helper function in my own project to map short routes:
void ShortRoute(string action, string controller)
{
ShortRoute(action, controller, action);
}
void ShortRoute(string action, string controller, string route)
{
_context.MapRoute(route, route, new { action, controller });
}
With usage:
ShortRoute("About", "Home");
Which allows me to navigate to mywebsite.com/about instead of mywebsite.com/home/about
If it's not working for certain URLs it may be that the route handler is matching a different route - I believe it does depend on the order you register them
There's a good route debugging plugin you can use
https://www.nuget.org/packages/routedebugger/
It gives you a summary of all routes and which ones matched the current URL - very useful
Without bringing in additional packages, you simply need to add an additional route. To create the new route, you first must define what you want your URL to be. In this case, you have said you want to be able to go to /Login which is on the user controller. Ok - let's create a new route. This route should be located ABOVE your default route.
routes.MapRoute(
"UserLogin",
"Login/{id}",
new { controller = "User", action="Login", id = UrlParameter.Optional }
);
The first parameter is simply the route name. The second parameter is the format of the URL that I want this route to match. Given we know what action we want to match to this route, we don't need the {action} or {controller} catchall placeholders that are in the default route. Also note that we can declare what controller this route will hit without having to specify the controller in the URL.
Last note, you don't have to have the {id} be part of the route if you will never be passing an ID parameter to that function. If that is the case, then you can safely remove any references to id in the UserLogin route.
As I re-read your question, you should be able to do this for some of your other examples as well. Let's take the /About URL and demonstrate the removal of the {id} parameter.
routes.MapRoute(
"AboutUsPage",
"About",
new { controller = "Home", action="About"}
);
This is very simple. You just need to create a route for each of your expected URLs.
Keep in mind that if you don't pass the controller or action as a URL placeholder, you will need to do so manually by providing them as default values.
routes.MapRoute(
"Blog",
"Blog/{id}",
new { controller = "Home", action = "Blog", id = UrlParameter.Optional }
);
routes.MapRoute(
"Login",
"Login/{id}",
new { controller = "User", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

MVC3 URL Routing

I am wanting to create a website that dynamically maps routes in the following fashion:
http://domain/MyCategory1
http://domain/
http://domain/MyCategory1/MySubCategory
So far I've added in a new route to Global.asax
routes.MapRoute(
"IFAMainCategory", // Route name
"{IFACategoryName}", // URL with parameters
new { controller = "Home", action = "GetSubCategories", IFACategoryName=1} // Parameter defaults
);
But this then messes up the default route that comes as standard.
Is there any way I can control this?
You need to change your routes:
routes.MapRoute("MyCustomRoute", "MyCategory1/{action}/{id}",
new { controller = "MyCategory1", action = "MySubCategory", id = UrlParameter.Optional });
// Then the default route
Basically, since you've just made one giant route catcher, all routes match to that one. You need to go specific if you want to map a specific route to a controller.
You need to include MyCategory1 in the route name
routes.MapRoute( "IFAMainCategory",
// Route name "MyCategory1/{IFACategoryName}",
// URL with parameters new { controller = "Home", action = "GetSubCategories", IFACategoryName=1} // Parameter defaults );
Check out this other post for example, and check out Route Debugger
.NET MVC custom routing
Unfortunately I don't think you're going to achieve what you want directly.
You need some way to separate the routes, like placing your "categories" in a folder:
routes.MapRoute(
"IFAMainCategory", // Route name
"categories/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "GetSubCategories", IFACategoryName=1 }
);
The other option is you could register a route for every parent category before the default route on App Start:
routes.MapRoute(
"IFAMainCategory 1", // Route name
"MyCategory1/{subcategory}", // URL with parameters
new { controller = "Home", action = "GetSubCategories", IFACategoryName=1, subcategory = UrlParameter.Optional }
);
routes.MapRoute(
"IFAMainCategory 2", // Route name
"MyCategory2/{subcategory}", // URL with parameters
new { controller = "Home", action = "GetSubCategories", IFACategoryName=2, subcategory = UrlParameter.Optional }
);

asp.mvc change controller name in request path

In my MVC project I have a controller names ProjectController and in path it looks like /project. I want to have the path for that "/proiect" .. is there any easy way to achieve that without renaming the controller class?
Thanks,
Radu
You should be able to accomplish this with routing
routes.MapRoute(
"Misspelling",
"proiect/{action}",
new { controller = "project", action = "index" }
);
Yes, you can modify the rewrite-rules in the Global.aspx file.
routes.MapRoute(
"Default", // Route name
"proiect/{action}/{id}", // URL with parameters
new { controller = "Project", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Asp.Net MVC Routes - Handle Multiple routes with the same signature?

I'm interested to know how people handle the following situation.
Assume we have a DataField and each DataField can have unlimited number of DataValues
We have 2 controllers to handle the manipulation of these objects
DataFieldController
DataValueContoller
Now if we ever need to add a new DataValue we need to know the ID of the CustomDataField. The following URL would be used,
/CustomDataValue/Add/1
1 = DataField ID
However, because the ASp.Net MVC engine binds the parameter name to the model (IE in the case below. My DatValeu Object would have its ID replaced, when I am actually trying to pass through the FieldID)
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Site", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);
How can we handle this? Doing the following obviously will not work.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Site", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{fieldid}", // URL with parameters
new { controller = "Site", action = "Home", fieldid = UrlParameter.Optional } // Parameter defaults
);
I assume this is a common problem, I just cant find the obvious solution at the moment. It would be ok if the Signature was differant but both are /String/String/Int
==========================
How can these routes work then?
/DataValue/Add/{DataFieldID}
/DataValue/Edit/{ID}
/DataValue/List/{DataFieldID}
Must I add 3 routes?
Use constraints in routes like this:
routes.MapRoute(
"Default", // Route name
"CustomDataValue/{action}/{fieldid}", // URL with parameters
new { controller = "Site", action = "Home", fieldid = UrlParameter.Optional } // Parameter defaults
);
It makes sure only URLs starting with "CustomDataValue" calls this route. It's declared as a constant, different from the default route. Make sure these specified routes are declared before the default route. Since there are no restrictions, all URLs are matched to it.
Update
I guess you have to call DataValueController methods with URLs like http://domain.com/CustomDataValue/Add/23. If that's the case use the following route:
routes.MapRoute(
"CustomData", // Route name
"CustomDataValue/{action}/{fieldid}", // URL with parameters
new { controller = "DataValue", action = "List", fieldid = UrlParameter.Optional } // Parameter defaults
);
This will work if you have action methods in DataValueController named List/Add/Edit.

ASP.NET MVC - Removing controller name from URL

I want to remove the controller name from my URL (for one specific controller). For example:
http://mydomain.com/MyController/MyAction
I would want this URL to be changed to:
http://mydomain.com/MyAction
How would I go about doing this in MVC? I am using MVC2 if that helps me in anyway.
You should map new route in the global.asax (add it before the default one), for example:
routes.MapRoute("SpecificRoute", "{action}/{id}", new {controller = "MyController", action = "Index", id = UrlParameter.Optional});
// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );
To update this for 2016/17/18 - the best way to do this is to use Attribute Routing.
The problem with doing this in RouteConfig.cs is that the old route will also still work - so you'll have both
http://example.com/MyController/MyAction
AND
http://example.com/MyAction
Having multiple routes to the same page is bad for SEO - can cause path issues, and create zombie pages and errors throughout your app.
With attribute routing you avoid these problems and it's far easier to see what routes where. All you have to do is add this to RouteConfig.cs (probably at the top before other routes may match):
routes.MapMvcAttributeRoutes();
Then add the Route Attribute to each action with the route name, eg
[Route("MyAction")]
public ActionResult MyAction()
{
...
}
Here is the steps for remove controller name from HomeController
Step 1:
Create the route constraint.
public class RootRouteConstraint<T> : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
return rootMethodNames.Contains(values["action"].ToString().ToLower());
}
}
Step 2:
Add a new route mapping above your default mapping that uses the route constraint that we just created. The generic parameter should be the controller class you plan to use as your “Root” controller.
routes.MapRoute(
"Root",
"{action}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { isMethodInHomeController = new RootRouteConstraint<HomeController>() }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Now you should be able to access your home controller methods like so:
example.com/about,
example.com/contact
This will only affects HomeController. All other Controllers will have the default routing functionality.
If you want it to apply to all urls/actions in the controller (https://example.com/action), you could just set the controller Route to empty above ApiController. If this controller going to be your starting controller, you'll also want to remove every launchUrl line in launchSettings.json.
[Route("")]
[ApiController]
You'll have to modify the default routes for MVC. There is a detailed explanation at ScottGu's blog:
http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
The method you should change is Application_Start. Something like the following might help:
RouteTable.Routes.Add(new Route(
Url="MyAction"
Defaults = { Controller = "MyController", action = "MyAction" },
RouteHandler = typeof(MvcRouteHandler)
}
The ordering of the routes is significant. It will stop on the first match. Thus the default one should be the last.
routes.MapRoute("SpecificRoute", "MyController/{action}/{id}",
new {controller = "MyController", action = "Index",
id = UrlParameter.Optional});
// default route
routes.MapRoute("Default", "{controller}/{action}/{id}",
new {controller = "Home", action = "Index",
id = UrlParameter.Optional} );

Resources