ASP.NET MVC C# Multiple Url Routes Config Controller Action - c#

I want create route config multiple Url. ex: "fr-ca/user/login" and "en-ca/user/login" and its working, but if click submit and proccess data by controller and return RedirectToAction(MVC.User.Dashboard); always return "fr-ca/user/dashboard";
Although I use Url "en-ca/", and always return all link MVC.anything in first is "fr-ca/"
Because in position route config, "fr-ca" is first.
Maybe somebody can help me to solve this, thank u.
routes.MapRoute(
name: "fr-Default",
url: "fr-ca/{controller}/{action}/{id}",
defaults: new { controller = MVC.Content.Name, action = MVC.Content.ActionNames.Show, id = UrlParameter.Optional, siteId = Site.FR.Id },
namespaces: new string[] { "Jay.Cms.Web.Controllers" }
);
routes.MapRoute(
name: "en-Default",
url: "en-ca/{controller}/{action}/{id}",
defaults: new { controller = MVC.Content.Name, action = MVC.Content.ActionNames.Show, id = UrlParameter.Optional, siteId = Site.EN.Id },
namespaces: new string[] { "Jay.Cms.Web.Controllers" }
);

You can write to action attribute in controller
'[Route("fr-ca/{controller}/{action}/{id}")]
[Route("en-ca/{controller}/{action}/{id}")]
public ActionResult Home()
{
return View();
}'

Related

What should be an MVC route for this URL?

I need to define an MVC route for URL like this:
http://localhost/RealSuiteApps/RealHelp/-1/Detail/BRK18482020
where:
Detail - is controller name
default action Index should be executed
-1 is some client id
BRK18482020 is orderId
I need this to go to DetailController, Index action with orderId parameter.
I tried this:
routes.MapRoute(
name: "Detail",
url: "Detail/{id}",
defaults: new { clientid = "-1", controller = "Detail", action = "Index", id = UrlParameter.Optional }
);
but I get a message "Page Not Found". What am I missing here ??
Assuming DetailController action
public ActionResult Index(int clientId, string orderId) { ... }
Then route would be mapped as
routes.MapRoute(
name: "Detail",
url: "{cientId}/Detail/{orderId}",
defaults: new { clientid = "-1", controller = "Detail", action = "Index" }
);
Note that this should also be registered before any default routes.

Asp.net Mvc Route By Only Slug

I'm using ASP.NET MVC 4 with C#. I'm using areas and it's named like "Admin"
Here is my route config;
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(name: "PageBySlug",
url: "{slug}",
defaults: new {controller = "Home", action = "RenderPage"},
constraints: new {slug = ".+"});
routes.MapRoute(name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional},
namespaces: new[] { "Web.Frontend.Controllers.Controllers" });
}
}
I generated frontend page links like; "products/apple-iphone"
So I want to call them like this.
But the error is: The code can't get the controller / action method.
I used frontend page links like;
#Html.ActionLink(linkItem.Title, "RenderPage", routeValues: new {controller = "Home", slug = linkItem.PageSlug})
#Html.RouteLink(linkItem.Title, routeName: "PageBySlug", routeValues: new { controller = "Home", action = "RenderPage", slug = linkItem.PageSlug })
#linkItem.Title
#linkItem.Title
They are rendering url links like; http://localhost:1231/products/apple-iphone
It's like what I want. But when I click any link, asp.net mvc gives me this 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: /products/apple-iphone
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1069.1
Here is my controller;
namespace Web.Frontend.Controllers
{
public class HomeController : BaseFrontendController
{
public ActionResult Index()
{
return View();
}
public ActionResult RenderPage(string slug)
{
return View();
}
}
}
So how can I catch every link request like this combined slug and turn my coded view ?
The problem is, When you request products/iphone, the routing engine don't know whether you meant the slug "products/iphone" or the controller "products" and action method "iphone".
You can write a custom route constraint to take care of this. This constraint will check whether the slug part of the urls is a valid controller or not, if yes,the controller action will be executed.
public class SlugConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
var asm = Assembly.GetExecutingAssembly();
//Get all the controller names
var controllerTypes = (from t in asm.GetExportedTypes()
where typeof(IController).IsAssignableFrom(t)
select t.Name.Replace("Controller", ""));
var slug = values["slug"];
if (slug != null)
{
if (controllerTypes.Any(x => x.Equals(slug.ToString(),
StringComparison.OrdinalIgnoreCase)))
{
return false;
}
else
{
var c = slug.ToString().Split('/');
if (c.Any())
{
var firstPart = c[0];
if (controllerTypes.Any(x => x.Equals(firstPart,
StringComparison.OrdinalIgnoreCase)))
{
return false;
}
}
}
return true;
}
return false;
}
}
Now use this route constraint when you register your custom route definition for the slug. make sure you use {*slug} in the route pattern. The * indicates it is anything(Ex : "a/b/c")(Variable number of url segments- more like a catch all)
routes.MapRoute(name: "PageBySlug",
url: "{*slug}",
defaults: new { controller = "Home", action = "RenderPage" },
constraints: new { slug = new SlugConstraint() }
, namespaces: new string[] { "Web.Frontend.Controllers.Controllers" });
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
, new string[] { "Web.Frontend.Controllers.Controllers" });
you can provide only this type of link
#linkItem.Title
Because Routetable find your route using Route name provided by you. so controller name and action name is not necessary.

Missing something simple in getting mvc route to work

It's late, I've had a lot happen today and I must be missing something very simple.
I have a route such as this:
routes.MapRoute("RequestKey", "License/RequestKey/{apello}/{requestcipher}",
new { controller = "ProductKey", action = "RequestKey" },
new { apello = "", requestcipher = "" },
new[] { "....Controllers" }
My controller action:
[ChildActionOnly]
public string RequestKey(string apello, string requestcipher)
{
return "Yeah";
}
And the url doesn't hit the controller action....time for bed?
http://localhost:53764/License/RequestKey/qwerqewrqwr/zxcvzcvzcx
Your tags indicate that you are using ASP.NET MVC 4, then try this route mapping:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{param1}/{param2}",
defaults: new { controller = "Home", action = "Index", param1 = UrlParameter.Optional, param2 = UrlParameter.Optional }
);
If you have the possibility to upgrade to ASP.NET MVC 5 then you can use Attribute routing and you should then have the possibility to write custom routes next to your Controller Action methods like this..
[Route("License/RequestKey/{apello}/{requestcipher}")]
public string RequestKey(string apello, string requestcipher)
{
return "Yeah";
}

MVC routing only applying to certain action results

Do I have to route a special route for every action result in a controller, or do you do one route, and have to live by that standard thought the controller? I thought you could make a default route, and then a special route for any instance you wanted. I keep running into a problem where one of my routes will hit my action Results correctly, but then the others no longer work. This code is probably the wrong way, but hence why I am posting it here. PLease try to clarify this for me if you can. I understand that I am suppose to be able to do {controller}/{action}/{id} for example. So that should hit Settings/GetSite/{siteid} for the following
public ActionResult GetSite(int id);
Routes configuration:
routes.MapRoute(
"SettingsUpdateEnviorment",
"{controller}/{action}",
new { controller = "Settings", action = "UpdateProperties" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
name: "ProfileRoute",
url: "Profiles/{userId}",
defaults: new
{
controller = "Profile",
action = "Index",
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Settings", // Route name
"Settings/{id}", // URL with parameters
new { controller = "Settings", action = "Index" } // Parameter defaults
);
Controller Code:
public ActionResult Index(int id)
{
return View(model);
}
public ActionResult GetSite(int enviornmentID, string name)
{
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddSite(int id)
{
return RedirectToAction("Index", new { id = id });
}
So, the URL works as expected for Settings/1 to hit the Index actionresult Index(int id). Then, when I try to do the ActionResult for GetSite(int enviornmentID, string name) using the following actionLink:
#Html.ActionLink(site.Name, "GetSite", "Settings", new { enviornmentID = Model.Enviorment.EnvironmentID, name = site.Name }, null)
It creates the URL correctly as follows: Settings/GetSite?enviornmentID=1&name=CaseyTesting2, but gives me an error stating that I am trying to send a null value to my Index(int id) actionResult. I thought that since I am using the action name and it's same params, that MVC will figure the route out? Why is this not functioning for me, or what I am doing wrong? Thanks!
I realized what I was doing thanks to this article http://www.itworld.com/development/379646/aspnet-mvc-5-brings-attribute-based-routing. I was mixing up the order, when I had everything else correct. Then I was missing the param names being identical, when everything else was correct. So I kept having minor issues when trying to find the problem out. I also switched to MVC5's attribute routing, and like it much more.
So this is my code that is now working:
RoutConfig
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "ProfileRoute",
url: "Profiles/{userId}",
defaults: new
{
controller = "Profile",
action = "Index",
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The controller code
[Authorize]
[RoutePrefix("settings")]
[Route("{action=index}")]
public class SettingsController : ZenController
{
[Route("{id:int}")]
public ActionResult Index(int id)
{
return View(model);
}
[Route("GetSite/{sitename:alpha}")]
public ActionResult GetSite(string sitename)
{
return RedirectToAction("Index");
}
Thanks again everyone! Happy coding!

Trying to format URL for Action using multiple params in MVC

I have the following action result:
public ActionResult Index(int id, int? siteId)
{
//code here....
return View(object);
}
I have the following route mapping as follows:
routes.MapRoute(
name: "SettingsRoute",
url: "Settings/{id}/{siteId}",
defaults: new
{
controller = "Settings",
action = "Index",
}
);
What do I need to do, so the url will be "Settings?id=1&siteId=133" instead of the format "Settings?id=1" durring initial load. Then to select a site it builds the URl "Settings/1/133".
I am using the following actionLink to create this:
<li>#Html.ActionLink(site.Name, "Index", "Settings", new { id = Model.SettingsEnvironment.EnvironmentID, siteId = site.SiteID }, null)</li>
I can't seem to get the routing down right. Any help would be appreciated. Thanks.
You need to set your optional URL parameter:
routes.MapRoute(
name: "SettingsRoute",
url: "Settings/{id}/{siteId}",
defaults: new
{
controller = "Settings",
action = "Index",
siteId = UrlParameter.Optional
}
);
ref: http://haacked.com/archive/2010/02/12/asp-net-mvc-2-optional-url-parameters.aspx/

Categories

Resources