I faced with the following problem. I have an url and I would like to check whether the url could be mapped to any route defined in my RouteConfig or not. In other words I need a right way to determine whether the url is correct for my application or not.
Maybe anyone knows how to do it?
For Example : Student is my contoller and having action method StudentList then I need to write following code in RouteConfig.cs file.
StudentContoller.cs
public List<Student> StudentList (StudentModel model)
{
/* Logic for Student List */
return View(model);
}
RouteConfig.cs
routes.MapRoute(
name: "StudentList",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student", action ="StudentList", id = UrlParameter.Optional }
);
Related
I have created a controller and I don't want my default Action or View to be named Index. I created Action in TopicsController as below
[ActionName("Index")]
public ActionResult Topics()
{
var topic = new Topic();
return View("Topics", topic.GetTopics());
}
and it mached to URL xyz.com/Topics.
I tried to apply same philosophy to another controller, named, ModulesController but now I have got parameter.
[ActionName("Index")]
public ActionResult Modules(string id)
{
var topic = new Topic();
return View("Modules", topic.GetTopics());
}
but now it is saying
The resource cannot be found.
what I can do so that this action matches URL like xyz.com/Modules/aaaa?
To access the Url xyz.com/Modules/aaaa change the Action name for the Modules action to aaaa like this:
[ActionName("aaaa")]
public ActionResult Modules(string id)
{
var topic = new Topic();
return View("Modules", topic.GetTopics());
}
FYI - It would be better to avoid naming each action with the ActionName filter. At some point it would become difficult to manage. Instead manage the routes in the RouteConfig like this:
routes.MapRoute(
name: "Modules",
url: "{controller}/{action}/{id}",
defaults: new { controller="Modules", action="Modules", id=UrlParameter.Optional }
);
The following Urls will work for the above route:
xyz.com/Modules/aaaa
xyz.com/Modules/aaaa/123
xyz.com/Modules/aaaa?id=123
Update:
If you want 'aaaa' to be the parameter and want to access the action with xyz.com/Modules/aaaa (where 'aaaa' will be bound as the value to the Id variable) then add the following Route to the route table:
routes.MapRoute(
name: "Modules",
url: "Modules/{id}",
defaults: new { controller="Modules", action="Modules", id=UrlParameter.Optional }
);
Note the value of the Url above.
Is there a way to have different routing based upon controller's action?
For example:
Default routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
this would make the url look like
localhost:/Home/{someaction}/{id}
if the controllers action is
public ActionResult SomeAction(int id)
{
return Content("Sup?");
}
but lets suppose I have this action
public ActionResult AnotherAction(Guid productCategoryId, Guid productId)
{
return content("Hello!");
}
if I don't have any custom routing then the route would look like
localhost:/Home/AnotherAction?productCategoryId=someGuidId&productId=someGuidId
but for this action if I want the route to look like
localhost/Home/AnotherAction/productCategoryGuidId/productGuidId
how would I do that?
I have added a custom route
routes.MapRoute(
name: "appointment",
url: "{controller}/{action}/{appointmentId}/{attendeeId}",
defaults: new {controller = "Home",action = "Index", appointmentId = "",attendeeId="" }
);
but how do I say a controller's action to use that route and not default route.
Also, I read there is attribute routing in MVC 5. Would this help in my case? How would I use it in my case?
Register your custom MapRoute before your default Route. The order of which come first counts in the table route.
Routes are applied in the order in which they appear in the RouteCollection
object. The MapRoute method adds a route to the end of the collection, which means that routes are generally applied in the order in which we add them.
Hope It will help
I am currently working on a beginner's MVC tutorial. I was wondering if anyone could explain how or where the parameters of this method are chosen?
public ActionResult Details(int id)
{
var album = storeDB.Albums.Find(id);
return View(album);
}
There are 2 ways your id parameter could be populated:
http://www.example.com/{Controller}/Details/{id}
or
http://www.example.com/{Controller}/Details?id={id}
where {Controller} is the name of your Controller, eg. The name of HomeController.cs would be "Home"
and where {id} is an int.
you're working with the default route I guess, so you gonna find in the Global.asax file the follow code:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
your route is that! where "id" is a optional parameter, suppose that your controller name is Album, so test http://mySite/Album/Details/10
you get a request where 10 is your Id parameter specify on the action Details
I have a action on my controller (controller name is 'makemagic') called 'dosomething' that takes a nullable int and then returns the view 'dosomething.aspx'. At least this is what I am trying to do. Seems no matter I get routed to the Default() view.
public ActionResult dosomething(int? id)
{
var model = // business logic here to fetch model from DB
return View("dosomething", model);
}
There is a /Views/makemagic/dosomething.aspx file that has the Inherits System.Web.Mvc.ViewPage
Do I need to do something to my routes? I have just the 'stock' default routes in my global.aspx.cs file;
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
I am calling the action via a href like this in another page;
Click Me!
Seriously driving me nutso. Any suggestions on how to troubleshoot this? I attempted to debug break on my route definitions and seems a break there doesn't happen as one would expect.
Change it so the parameter isn't nullable so it will match the default route, or change the name to something other than id and supply it as a query parameter. An example of the latter would be:
public ActionResult dosomething(int? foo)
{
var model = // business logic here to fetch model from DB
return View("dosomething", model);
}
Click me
The it will work with the default routing implementation. Alternatively, you could do something that would distinguish it from the default route and then you would be able to have a route for it and not have to use query parameters.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/foo/{id}", // URL with parameters
new { controller = "makemagic", action = "dosomething", id = "" } // Parameter defaults
);
Click Me!
ASP.NET MVC routes have names when mapped:
routes.MapRoute(
"Debug", // Route name -- how can I use this later????
"debug/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = string.Empty } );
Is there a way to get the route name, e.g. "Debug" in the above example? I'd like to access it in the controller's OnActionExecuting so that I can set up stuff in the ViewData when debugging, for example, by prefixing a URL with /debug/...
The route name is not stored in the route unfortunately. It is just used internally in MVC as a key in a collection. I think this is something you can still use when creating links with HtmlHelper.RouteLink for example (maybe somewhere else too, no idea).
Anyway, I needed that too and here is what I did:
public static class RouteCollectionExtensions
{
public static Route MapRouteWithName(this RouteCollection routes,
string name, string url, object defaults, object constraints)
{
Route route = routes.MapRoute(name, url, defaults, constraints);
route.DataTokens = new RouteValueDictionary();
route.DataTokens.Add("RouteName", name);
return route;
}
}
So I could register a route like this:
routes.MapRouteWithName(
"myRouteName",
"{controller}/{action}/{username}",
new { controller = "Home", action = "List" }
);
In my Controller action, I can access the route name with:
RouteData.DataTokens["RouteName"]
If using the standard MapRoute setting like below:
routes.MapRoute( name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
...this will work in the view...
var routeName = Url.RequestContext.RouteData.Values["action"].ToString();
You could pass route name through route values using default value of additional parameter:
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{action}/{id}",
defaults: new { routeName = "MyRoute", controller = "Home", action = "Index", id=UrlParameter.Optional }
);
Then, it is possible to get passed value from controller context:
string routeName = ControllerContext.RouteData.Values["routeName"].ToString();
This does not directly answer the question (if you want to be pedantic); however, the real objective seems to be to get a route's base URL, given a route name. So, this is how I did it:
My route was defined in RouteConfig.cs as:
routes.MapRoute(
name: "MyRoute",
url: "Cont/Act/{blabla}",
defaults: new { controller = "Cont", action = "Act"}
);
And to get the route's base URL:
var myRoute = Url.RouteUrl("MyRoute", new { blabla = "blabla" }).Replace("blabla", "");
It gave me the route's base URL that I wanted:
/Cont/Act/
Hope this helps.
An alternative solution could be to use solution configurations:
protected override OnActionExecuting()
{
#if DEBUG
// set up stuff in the ViewData
#endif
// continue
}
There shouldn't really ever be a need to reference the route name like this - which I suppose is why MVC makes it so difficult to do this sort of thing.
another option - use MapRoute with string[] namespaces argument, then you can see your namespaces as RouteData.DataTokens["Namespaces"]