Response.RedirectToRoute with an action specified - asp.net-mvc

I wish to redirect to a route but also specify the action to run on that route's controller.
I tried this:
Response.RedirectToRoute("Login", new { action = "ChangePassword" });
The action looks like this:
public ActionResult ChangePassword()
{}
The route looks like this:
routes.MapRoute("Login", "Login/{action}", new { controller = "Login",
action = "Index" } );
The error I get is :
System.NotImplementedException: The method or operation is not implemented.
Can you see what I'm doing wrong?

I too had a hard time with this. I did this
Response.Redirect(Url.RouteUrl(new{ controller="controller", action="action"}));

Well, you only get NotImplementedException when something throws it. So look at the stack trace (Call Stack) and find the routine which threw it. When VS automatically implements an interface, for example, the body will throw this; you're expected to replace the implementation.

return Redirect(Url.RouteUrl(new { controller = "Controller", action = "Action" }));

Related

Redirect from a method in a class to an action result in a controller

I have a mvc application and when a user is authenticated,
a method is called from a class to determine the type of user.
I will like to do a redirect to an action result in a controller from a method in a class.
How do i redirect from a method in a class to an action result in a controller?
There might be a good reason for why you want to do it this way, but I want to suggest an alternative for you.
I would suggest that you redirect to an action based on the result from a method in a class, rather than doing the redirection in the method itself.
Pseudo-code:
public ActionResult Index()
{
var tmp = new YourClass();
if(tmp.UserType().Equals("Admin")
{
return RedirectToAction("Admin", "Home");
}
if(tmp.UserType().Equals("User"))
{
return RedirectToAction("User","Home");
}
}
First off, I think it's not a good practice to call controller actions from classes like you wish.
Your class will be tightly coupled to an MVC controller.
However it's feasible by doing this:
var context = new RequestContext(
new HttpContextWrapper(System.Web.HttpContext.Current),
new RouteData());
var urlHelper = new UrlHelper(context);
var url = urlHelper.Action("Index", new { OtherParm = "other value" });
System.Web.HttpContext.Current.Response.Redirect(url);
this example comes from this answer

Custom routes management

Is it possible to use custom routes handling code?
For example client requests server on http://server.com/api/v1/json/profile/ and my code calls ApiController, MyAction action with parameters version=1, format=json, action=profile.
Something like this? You'll have to use a different parameter name for action so you don't have a conflict with the controller action.
.MapRoute("name", "api/v{version}/{format}/{_action}", new { controller = "ApiController", action = "MyAction" });
EDIT made version work the way you wanted.
I would start off by renaming the "action" parameter to something else otherwise the route is going to get very confusing (maybe call it purpose?). Also, I believe something like the following would work:
routes.MapRoute(
// name of your route
"MyRoute",
// route template
"api/v{version}/{format}/{purpose}",
// default route values
new {
controller = "ApiController",
action = "MyAction",
},
// constraints placed on parameters (make sure they are valid)
new {
version = #"^\d+$", // number only (can also include decimals)
format = #"^(json|text|xml)$", // if you want filtering...
}
);
Then:
public ApiController : Controller
{
public ActionResult MyAction(Int32 version, String format, String purpose)
{
throw new NotImplementedException();
}
}

ASP.NET MVC RemoteAttribute: No url for remote validation could be found

How to configure RemoveAttribute to work with routes like this one?
context.MapExtendedRoute("ValidateSomething",
"some-where/validate/{propName}",
new { Controller = "SomeWhere", Action = "ValidateSomeRouteKey" });
When I pass above route name to RemoteAttribute constructor, an InvalidOperationException occurs. But works just like a charm when there is no propName in route definitions and parameter passed as querystring.
Thanks in advance;)
You need to add the {propname} parameter to your route, so that you can access it in your controller. In the example below I have made it optional.
context.MapExtendedRoute("ValidateSomething",
"some-where/validate/{propName}",
new { Controller = "SomeWhere", Action = "ValidateSomeRouteKey", propName = UrlParamter.Optional });

How can I pass the URL to the controller while routing ignores it?

Is there a way within asp.net MVC 2 whereby I can route a request and have a portion of the URL ignored and passed to the controller as a variable?
My needs state that I must store pages dynamically in a database, and they should be accessible by looking at the URL and reading the URL segments to find the relevant page. Effectively, I need a Site controller, to which the remaining portion of the URL will be passed.
Site-Controller/this/is/a/page
So this in case the site controller would pick up the /this/is/a/page 'string'
Is this possible?
Thanks!
Yes, use a wildcard route, like:
routes.MapRoute(
"SiteController", // Route name
"Site-Controller/{*url}", // URL with parameters
new { controller = "SiteController", action = "Index" }, // Parameter defaults
null // constraints
);
Then your action looks like:
public ActionResult Index(string url)
{
}
Create a wildcard Route in Global.asax which captures everything after the first segment of the url and passes it to your Action method:
routes.MapRoute("Page",
"Site-Controller/{*urlsegments}",
new {
controller = "Site-Controller",
action = "YourAction",
urlsegments = ""
});
Make sure your Action method accepts a 'urlsegments' parameter and you can work with it from there:
public ActionResult YourAction(string urlsegments)
{
// Do something with the segments here
}

ASP.NET MVC Map String Url To A Route Value Object

I am creating a modular ASP.NET MVC application using areas. In short, I have created a greedy route that captures all routes beginning with {application}/{*catchAll}.
Here is the action:
// get /application/index
public ActionResult Index(string application, object catchAll)
{
// forward to partial request to return partial view
ViewData["partialRequest"] = new PartialRequest(catchAll);
// this gets called in the view page and uses a partial request class to return a partial view
}
Example:
The Url "/Application/Accounts/LogOn" will then cause the Index action to pass "/Accounts/LogOn" into the PartialRequest, but as a string value.
// partial request constructor
public PartialRequest(object routeValues)
{
RouteValueDictionary = new RouteValueDictionary(routeValues);
}
In this case, the route value dictionary will not return any values for the routeData, whereas if I specify a route in the Index Action:
ViewData["partialRequest"] = new PartialRequest(new { controller = "accounts", action = "logon" });
It works, and the routeData values contains a "controller" key and an "action" key; whereas before, the keys are empty, and therefore the rest of the class wont work.
So my question is, how can I convert the "/Accounts/LogOn" in the catchAll to "new { controller = "accounts", action = "logon" }"??
If this is not clear, I will explain more! :)
Matt
This is the "closest" I have got, but it obviously wont work for complex routes:
// split values into array
var routeParts = catchAll.ToString().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
// feels like a hack
catchAll = new
{
controller = routeParts[0],
action = routeParts[1]
};
You need to know what part is what in the catchAll parameter. Then you need to parse it yourself (like you are doing in your example or use a regexp). There is no way for the framework to know what part is the controller name and what is the action name and so on, as you haven't specified that in your route.
Why do you want to do something like this? There is probably a better way.

Resources