Url Routing Help Asp.net Mvc - asp.net-mvc

I have three url types. These:
first: http://localhost/
second: http://localhost/X/
third: http://localhost/X/Y/
Examples Url:
http://localhost/test/
http://localhost/test/details/
first:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
second:
routes.MapRoute(
"Module",
"{module_name}/{controller}/{action}",
new
{
controller = "Module",
action = "Index",
module_name = UrlParameter.Optional
}
);
public class ModuleController : Controller
{
//
// GET: /Module/
public ActionResult Index(string modul_name)
{
return View();
}
}
third:
routes.MapRoute(
"ModuleDetails",
"{module_name}/{details_param}/{controller}/{action}",
new
{
controller = "ModuleDetails",
action = "Index",
module_name = UrlParameter.Optional,
details_param = UrlParameter.Optional
}
);
public class ModuleDetailsController : Controller
{
//
// GET: /ModuleDetails/
public ActionResult Index(string modul_name, string details_param)
{
return View();
}
}
in this instance;
http://localhost/X/
response: "Home", "Index"
but;
http://localhost/X/
response: Application in the server error. Resource Not Found.
http://localhost/X/Y/
response: Application in the server error. Resource Not Found.
How can I do?
Thanks, best regards..

http://localhost/X/
response: Application in the server error. Resource Not Found.
This happens because each of your routes specifies at least 2 mandatory parameters.
Try to add this one:
routes.MapRoute(
"Default",
"{controller}/{action}",
new
{
controller = "Home",
action = "Index"
}
);

that's right friends..
routes.MapRoute(
"Default", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Module",
"{modul_name}",
new { controller = "Modul", action = "Index", modul_name = UrlParameter.Optional }
);
routes.MapRoute(
"Page",
"{modul_name}/{page_name}",
new { controller = "Page", action = "Index", modul_name = UrlParameter.Optional, page_name = UrlParameter.Optional }
);

Related

How to display only name in url instead of id in mvc.net using routing

I am getting url like http://localhost:49671/TestRoutes/Display?f=hi&i=2
I want it like http://localhost:49671/TestRoutes/Display/hi
I call it from Index method.
[HttpPost]
public ActionResult Index(int? e )
{
// return View("Display", new { f = "hi", i = 2 });
return RedirectToAction("Display", new { f = "hi", i = 2 });
}
Index view
#model Try.Models.TestRoutes
#using (Html.BeginForm())
{
Model.e = 5 ;
<input type="submit" value="Create" class="btn btn-default" />
}
Display Action method
// [Route("TestRoutes/{s}")]
public ActionResult Display(string s, int i)
{
return View();
}
Route config file
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
});
You need to change your route definition to
routes.MapRoute(
name: "Professional",
url: "TestRoutes/Display/{s}/{i}",
default: new { controller = "TestRoutes", action = "Display", i = UrlParameter.Optional }
);
so that the names of the placeholders match the names of the parameters in your method. Note also that only the last parameter can be marked as UrlParameter.Optional (otherwise the RoutingEngine cannot match up the segments and the values will be added as query string parameters, not route values)
Then you need to change the controller method to match the route/method parameters
[HttpPost]
public ActionResult Index(int? e )
{
return RedirectToAction("Display", new { s = "hi", i = 2 }); // s not f
}
change your route as
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{name}", // URL with parameters
new
{
controller = "TestRoutes",
action = "Display"
} // Parameter defaults
);
and your action as
public ActionResult Display(string name)
{
//action goes here
}
Remove the maproute code:
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
Use attribute routing code:
[Route("TestRoutes/{s}/{i?}")]
public ActionResult Display(string s, int? i)
{
return View();
}
You can also try using Attribute Routing. You can control your routes easier with attribute routing.
Firstly change your RouteConfig.cs like that:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
}
}
After that change your controller files like that:
namespace YourProjectName.Controllers
{
[RoutePrefix("Home")]
[Route("{action}/{id=0}")]
public class HomeController : Controller
{
[Route("Index")]
public ActionResult Index()
{
return View();
}
[Route("ChangeAddress/{addressID}")]
public ActionResult ChangeAddress(int addressID)
{
//your codes to change address
}
}
You can also learn more about Attribute Routing in this post:
https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/
Another way to solve this problem is to put the proper route before the default route, as follows:
routes.MapRoute(name: "MyRouteName", url: "Id", defaults: new { controller= "Home", action = "Index",id= Id });
Default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{Id}",
defaults: new { controller = "Home", action = "Index",id= Id }
);

UrlParameter.Optional not working in Razor

I am using below code in layout for links:
But it's not working, here is my route Config
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 }
);
}
This is my NewProduct Controller:
public ActionResult NewProduct(int id = -1)
{
NewProductModel m = new NewProductModel();
return View(m);
}
What is problem in my UrlParameter.optional
When you using #Url.Action helper you should pass the actual value to parameter like this:
#Url.Action("NewProduct", "Administrator", new { id = 1 })
UrlParameter.Optional should be used only in RouteConfig as you see in your code.
in NewProduct controller :
public ActionResult NewProduct(int id = -1)
{
NewProductModel m = new NewProductModel();
m.Id = id;
return View(m);
}
and for Link

ASP.NET MVC 5 - Removing controller name from url fails for other controllers

I followed the answer to this question but when I apply it I get an error if I try to access views under other controllers.
If I go to http://mydomain/MyActionUnderHome it works fine, but if I go to http://mydomain/SomeOtherController/MyAction it throws
"The resource cannot be found."
Shouldn't the Default route take over if the URL doesn't match the route definition above the Default route?
Are there perhaps new ways in MVC 5 to do this?
My routes:
routes.MapRoute(
"HomeRoute",
"{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"AccountRoute",
"{action}/{id}",
new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Better to use Route attribute.
public class HomeController : Controller
{
[Route("")]
public ActionResult Index() { return View(); }
[Route("MyAccount")]
public ActionResult Account() { return View(); }
}
Then add this line t your RouteConfig class before the routes.MapRoute
routes.MapMvcAttributeRoutes();
The issue is that you have is conflicting routes that the router can't resolve correctly
routes.MapRoute(
"HomeRoute",
"{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"AccountRoute",
"{action}/{id}",
new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
When the router looks at the path /youraction/yourparameter it will resolve to the first route.
The next part of this is that when you provide two values as your URL (as in your example the default router never gets called because the router interprets your input as /action/id rather than controller/action/id
If you change your routes to be:
routes.MapRoute(
"HomeRoute",
"index/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Then you'll get your effect. But your second route can still never be called, as your scheme isn't correct.

ASP MVC getting GET request instead of POST

I have next specific map routes
routes.MapRoute(
"MyPagePost",
"URL-Up/{name}",
new { controller = "MyController", action = "MyPostAction" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
"MyPageGet",
"URL-Up/{name}",
new { controller = "MyController", action = "MyGetAction" },
new { name = "[A-Za-z].+", httpMethod = new HttpMethodConstraint("GET") }
);
my default controller looks like
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", culture = "en", id = UrlParameter.Optional },
constraints: new { culture = #"[a-zA-Z]{2}" }
);
and the issue is next:
my get MyPageGet route show a page with include FORM with POST reqvest to MyPagePost route, but on a first call I am getting the same GET request and see in URL other extra param ?culture=de. Moreover, with or without this parameter, second call it working fine via MyPagePost route.
UPDATE:
In Chrome or fiddler Logs I see that reqvest to URL-Up/Bla-Bla has 302 status and response heared is URL-Up/Bla-Bla?culture=de. Why it can't be processed ?
just try it with
#using(Html.BeginRouteForm("MyPagePost",FormMethod.Post))
{
<input type="submit" value="Submit"/>
}
The routes in your post working for me in both html.beginform and html.beginrouteform on the first time.
i try it with the following routes and action methods
routes.MapRoute(
"MyPagePost",
"URL-Up/{name}",
new { controller = "Home", action = "PostAction" },
new { name="[A-Za-z].+", httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
"MyPageGet",
"URL-Up/{name}",
new { controller = "Home", action = "GetAction" },
new { name = "[A-Za-z].+", httpMethod = new HttpMethodConstraint("GET") }
);
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", culture = "en", id = UrlParameter.Optional },
constraints: new { culture = #"[a-zA-Z]{2}" }
);
public ActionResult GetAction()
{
return View();
}
[HttpPost]
public ActionResult PostAction()
{
return View();
}

asp mvc 5 Attribute routing not firing

I'm trying to use the attribute routing in a new project, but I can't get it to work.
Here is what I have so far :
[RoutePrefix("Product")]
public class ProductController : Controller
{
[Route("{id}/{title}", Name = "Product Details")]
public ActionResult Index(int id = 0, string title = "")
{
Product p = Product.Get(id);
return View(p);
}
}
And here is my RouteConfig.cs :
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// "Product Details",
// "Product/{id}/{title}",
// new { controller = "Product", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional }
//);
routes.MapRoute(
name: "DefaultIndex",
url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
If I remove the Routing attributes and uncomment the first route in my RouteConfig.cs it works fine, but I'd like to stick with route attributes.
Any idea why it's not working correctly ?
The URL I want to use is : http://www.mydomain.com/Product/12345/ProductName
EDIT, here is my Application_Start()
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleMobileConfig.RegisterBundles(BundleTable.Bundles);
}
Looks like its treating the {id} as an action.
Try this:
[Route("{id:int}/{title}", Name = "Product Details")]
Or this
[Route("Product/{id}/{title}", Name = "Product Details")]

Resources