I have a web application developed in ASP.NET MVC3 with C# and Razor.
I would like to call a specific Action Method of a specific Controller by using the ActionLink HTML helper. I know that the second parameter of ActionLink specifies the Action Method to be called from the Default route, which is the only one in my Global.asax file:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Index", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
I would like to call the Download Action Method from the Home Controller instead of Index. This does not work:
#Html.ActionLink("Presentation", "Download", "Home", new { topicId = topic.TopicId } )
It requires as third parameter a type Object but I cannot find on the web any example.
What are the steps needed in order to call a specific Controller/ActionMethod? Shall I create another route in my Global.asas file?
Thanks
Try this one:
#Html.ActionLink("Download", "Download", new { controller = "Home", Id = topic.TopicId });
The third parameter, object: routeValues, is used as dictionary in Asp.net MVC. Phil Haacked blogged about the decision for using object as route values.
update:
Your overload function is not working because you are calling this method. String is also object. So, you are passing "Home" as routeValues and new { topicId = topic.Id} as htmlAttributes. :)
Is this the overload you require? You will need the 5th parameter for html attributes.
#Html.ActionLink("Presentation", "Download", "Home", new { topicId = topic.TopicId }, new { name="Download" )
Related
I have this following url:
http://www.example.com?user=Ana
and I want to get http://www.example.com?Ana
How can I get it?
You can route example.com/Ana to Home/Index with parameter (you can change controller and action to what is needed). Just add new route to your routing dictionary
routes.MapRoute(
"UserPage",
"{controller}/{action}/{user}",
new { controller = "Home", action = "Index", user = "" }
);
You can read more about routing here at ASP.NET
NOTE:
as Alexei Levenkov said it requires .Net MVC to route it that way.
Let's say I have only this route:
routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
We can see that our startup page will be Home/Index.
And let's say I have created an anchor element using this code in the view:
#Html.ActionLink("This targets another controller","Index", "Admin")
When I render the view, you will see the following HTML generated:
This targets another controller
Our request for a URL that targets the Index action method on the Admin controller has been expressed as /Admin by the ActionLink method. The routing system is pretty clever and it knows that the route defined in the application will use the Index action method by default, allowing it to omit unneeded segments.
And the question is:
If I change the route as:
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{name}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
name = UrlParameter.Optional
});
or as:
routes.MapRoute("Default", "{controller}/{action}/{id}/{*catchall}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
Then, the following HTML will be generated:
This targets another controller
Could you explain me why?
Both:
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{name}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
name = UrlParameter.Optional
});
and:
routes.MapRoute("Default", "{controller}/{action}/{id}/{*catchall}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
are invalid route definitions because only the last segment of a route can be optional. Otherwise the routing engine cannot disambiguate your routes.
Now back to your original question as why for those routes the framework doesn't infer the /Index part. This is because the framework, when evaluating your route pattern it sees this:
{controller}/{action}/{id}/{name}
See that {id} portion of your route? When it analyzes this pattern it knows in advance that the {action} part is followed by a non optional segment ({id} in your case) which you must always be present. And since it knows that it, is pretty obvious that it cannot be clever and omit the /Index part and it doesn't even try to. On the other hand you can specify a default value for your last segment and it will be omitted when generating routes with this value.
PLEASE MARK AS DUPLICATE - Its already answered here
Is it possible to have a parameter named action in MVC4?
Trying to do this results in the parameter returning me the name of the controller action rather than the parameter value.
/Somecontroller/Someaction?action=value
When I try to access the parameter action, I get "Someaction" as the result rather than "value".
Trying to bind the parameter to a different name doesn't help either.
public ActionResult Someaction([Bind(Prefix = "action")] String id)
Edit: I have not found 'Action'/'action' in reserved MVC keywords either.
I haven't tested this, but I would assume you could try changing the url of your default route to something other than action
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
to
routes.MapRoute("Default", "{controller}/{cAction}/{id}",
new { controller = "Home", cAction = "Index", id = UrlParameter.Optional });
this should then allow you to use action as a parameter in your Action. I'm not certain why you'd want to do this, I would probably build a route url that accepted my action and built it as part of the url similar to this:
/SomeController/SomeAction/value where value is your "action" parameter.
EDIT based on comments:
I successfully created a route that goes to an aspx url'd route
routes.MapRoute(null, "third-party.aspx", new { controller = "Home", action = "Index" });
Obviously you can add whatever controller/action you want here and where you want to handle it, then you access that route via /third-party.aspx?action=value and it seemed to work for me
I have an ASP.NET MVC routing question. First, let me explain my areas setup. It's quite simple.
Areas
|
+--Foo
|
+--Controllers
|
+--BarController.cs
I have a folder in my areas called "Foo" and controller called "BarController.cs" The Bar controller has several methods named "DoStuff1()", "DoStuff2()", etc.
My website uses the following URLs:
/foo/bar/15
/foo/bar/dostuff1
/foo/bar/dostuff2
The first URL requires an id and uses the default Index() method in the Bar controller to populate the webpage with a view and model.
In the second and third URLs, I'm using them for jQuery ajax calls.
Here is the code from my area registrion
context.MapRoute(null, "Foo/Bar/DoStuff1", new
{
action = "DoStuff1",
controller = "Bar"
});
context.MapRoute(null, "Foo/Bar/DoStuff2", new
{
action = "DoStuff2",
controller = "Bar"
});
context.MapRoute(null, "Foo/Bar/{id}", new
{
action = "Index",
controller = "Bar"
});
My problem is that for each new controller method I create, I have to add another route mapping in the area registrion file. For example, if I add the method DoStuff3(), I'll need to add this to the area registration:
context.MapRoute(null, "Foo/Bar/DoStuff3", new
{
action = "DoStuff3",
controller = "Bar"
});
How can I create a generic route mapping to handle the URLs I mentioned above that doesn't require new additions to the area registration file for new controller methods?
You can pull out the controller action.
Write the URL like this:
"Foo/Bar/{action}"
Additionally, you can pull out the controller as well, and write
"Foo/{controller}/{action}"
In this case, action = "Index" provides a default value of "Index" if no action parameter is provided.
In this case, you need to disambiguate between "Foo/Bar/{action}" and "Foo/Bar/{id}". Since matching is done in order, you'll want to put the id route first, and add a numeric constraint to the id parameter. This allows valid numeric ids to match it, and action names to skip down to the next route. Your two routes would look like this:
context.MapRoute(null, "Foo/Bar/{id}", new
{
action = "Index",
controller = "Bar"
},
new { id = #"\d+" });
context.MapRoute(null, "Foo/Bar/{action}", new
{
action = "Index", //optional default parameter, makes the route fall back to Index if no action is provided
controller = "Bar"
});
The default routing that comes with MVC templates are good for most of the needed route configurations.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:
http://site/catalogue/BrowseByStyleLevel/1
The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.
For example, these two URLs will take you to the same place:
https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages
https://stackoverflow.com/questions/119323/
EDIT: The friendly part of the url is referred to as a slug.
There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter:
routes.MapRoute( "Default", // Route name
"{controller}/{action}/{id}/{ignoreThisBit}",
new { controller = "Home",
action = "Index",
id = "",
ignoreThisBit = ""} // Parameter defaults )
Now you can type whatever you want to at the end of your URI and the application will ignore it.
When you render the links, you need to add the "friendly" text:
<%= Html.ActionLink("Link text", "ActionName", "ControllerName",
new { id = 1234, ignoreThisBit="friendly-text-here" });
This is how I have implemented the slug URL on my application.
Note: The default Maproute should not be changed and also the routes are processed in the order in which they're added to the route list.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute("Place", "{controller}/{action}/{id}/{slug}", new { controller = "Place", action = "Details", id = UrlParameter.Optional,slug="" });
you have a route on the global.asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = ""}
// Parameter defaults )
you can define your own route like :
controller is the cs class inside the the controllers folder.
you can define your id - with the name you choose.
the system will pass the value to your actionResult method.
you can read more about this step here : http://www.asp.net/learn/mvc/tutorial-05-cs.aspx