MVC 5 - Redirect to a controller from anywhere - redirect

I am developing a MVC 5 internet application, and I wish to redirect to a controller/action result from anywhere in my application.
The controller name is "Manager", and the action result is "TestAction"
In an action result, the following code can be used:
RedirectToAction("TestAction", "Manager")
I have also coded a filter attribute as follows:
filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary{{ "controller", "Manage" }, { "action", "TestAction" } });
Is there a generic way to send the user to a specific controller, action result from anywhere in a MVC application? I specifically wish to do this in an extension method.
Thanks in advance.

You can do it by simply Response.Redirect (taking the domain path and append the url).
Did you try the answer like this one https://stackoverflow.com/a/18126733/713789

In your controller you can use RedirectToAction("TestAction", "Manager") to redirect and in your view you can write windows.location.href("Manager","TestAction").

What i've done in such cases:
Dictionary<string, object> dictionary = new Dictionary<string, object>();
//
//...add parameters...
dictionary.Add("controller", "ControllerName");//ex: Home for HomeController
dictionary.Add("action", "MyMethod");
return RedirectToRoute("Default", dictionary);//"Default" is the name of the rout you're using

Related

Generating link using urlhelper in MVC 6 controller (vNext)

I am trying to learn the new MVC 6. I never used the Microsoft MVC framework before.
I am trying to enhance an simple tutorial web API by adding links to different actions of my controllers using the URL (urlhelper) of the controller (Home controller showing what the API can do).
But when I use:
this.Url.Action("Get", new {id = id});
I get a query string with the URL. I'd like a more restful-style URL.
I thought when using the attributes routing, I do not have to map a specific route like I see in old tutorials of WebApi.
Do I have to map a route ?
What do I have to do to get a more restful URL style ?
You can add a name to the route attributes in your controller, then use the extension method IUrlHelper.RouteUrl to generate the url.
For example, given the following web api controller:
[Route("api/[controller]")]
public class UsersController : Controller
{
// GET: api/users
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/users/5
[HttpGet("{id}", Name ="UsersGet")]
public string Get(int id)
{
return "value";
}
//additional methods...
}
You can generate the url api/users/123 for the specific get by id action using #Url.RouteUrl("UsersGet", new { id = 123 }).
The problem when using the Url.Action extension method is that if you have a controller like in the example above with 2 actions named "Get", this will use the route for the action without parameters and generate /api/Users?id=123. However if you comment that method, you will see that #Url.Action("Get", "Users", new { id = 123 }) also gives you the expected url.

MVC Routing: How to route /mypath/Default.aspx to /Default.aspx and keep QueryString?

We upgraded our solution to MVC 2. Outside links are still using /mypath/Default.aspx with a query string of n=10. Is there any way to catch that route with a controller and call a Default.aspx file with the proper query string?
We tried simply rerouting with IIS6 as well as a meta refresh, but both strip off the query string.
Nick Craver's answer looks promising as an answer to this question.
I'm not sure what you mean by "and call a Default.aspx file with the proper query string?" but if you mean to call your default route, then it can easily be done.
You should be able to just specify a route on "mypath/Default.aspx". The querystring will be automatically bound to your method.
For example:
routes.MapRoute(
"LegacyUrl", // Route name
"mypath/Default.aspx", // URL with parameters
new { controller = "Home", action = "Index"}
);
Then your method:
[HttpGet]
public ActionResult Index(int n)
{
// do something with n, maybe pass it to the View
return View();
}

Inconsistent Routing Results in MVC

Seems I'm still missing something to the MVC routing concept. I have a route that follows nearly the same pattern as another route in an area but for what ever reason I get a 404 every time I attempt to run it. I've tried to use Phil Haack's Route Tester DLL and according to that it hits the correct route (matched route comes out to common/itemhistory/{contentid}). When I try to run it for real, it blows up.
I'm trying to map a call to a JsonResult by passing a Guid. I've had success with other routes working fine (common is an area in my site).
What could I be doing wrong?
context.MapRoute(
"ItemHistory",
"common/itemhistory/{contentid}",
new { controller = "common", action = "GetItemHistory" },
new { contentid = #"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$" }
);
context.MapRoute(
"Common_default",
"common/{action}",
new { controller="common", action = "Index" }
);
You are assigning action attribute to "GetItemHistory" and have defined itemhistory in the regular Route Pattern. Looks like you don't have a method in your controller by name "GetItemHistory"

MapRoute (Asp.Net MVC 2.0 .NET 4.0)

is there any possibility to create a maproute which would use always one method and it won't be necessary to put it in address?
I mean I've got controller with one method (Index) and it displays items depend on methods argument.
public ActionResult Index(string TabName)
{
var tab = (from t in BlogDB.Tabs
where t.TabName == TabName
select t).SingleOrDefault();
ViewData.Model =(Tab)tab;
return View();
}
and what I want is that I can display items putting address "www.example.com/Tabs/TabName" without "/Index/" between Tabs and TabName. I've tried:
routes.MapRoute(
"Tabs1",
"Tabs/{TabName}",
new { controller = "Tabs", action = "Index", TabName = UrlParameter.Optional }
);
But it doesn't work.
do you still have the default route? and if yes is it defined before this one?
Your problem is that asp.net mvc is trying to find the Tabs controller and the Tabname action.
Put this route before the default {controller}/{action} route

ASP.NET MVC 2.0: How to read querystring value

I am trying to build a small ASP.NET MVC 2 application.I have a controller class with the below method in it
public ActionResult Index()
{
TestMvc.Models.PersonalInformation objPerson = new TestMvc.Models.PersonalInformation();
objPerson.FirstName = "Shyju";
objPerson.LastName = "K";
objPerson.EmailId="shyju#company.com";
return View(objPerson);
}
And when the page (View) being called, i can see this data there as my view has these data's displaying. Now i want to know how can i pass a query string in the url and use that id to build the PersonalInformation object.Hoe can i read the querystring value ? Where to read ?
I want the quesrtstring to be like
http://www.sitename/user/4234 where 4234 is the user id
http://www.sitename/user/4234 is not a querystring. The querystring is the part of the URL that comes after the ?, as in http://www.sitename/user?userId=42
However, the default routes that come with the MVC project template should allow you to simply change the signature of your action method to
public ActionResult Index(int id)
and you should get the desired result. You should look into how routing works in MVC if you want full control of your URLs.
Also, note that the index action is usually used for showing a list of all objects, so you probably want the Details action for showing 1 user object.
What you want is to modify your action to accept an id like so:
public ActionResult Index(string id)
{
TestMvc.Models.PersonalInformation objPerson = new TestMvc.Models.PersonalInformation();
if (!string.isNullOrEmpty(id))
{
objPerson = getPerson(id);
}
return View(objPerson);
}
Then add a route to your global.asax:
routes.MapRoute(
"MyRoute", // Route name
"user/{id}", // URL with parameters
new { controller = "mycontroller", action = "index", id = ""} // Parameter defaults
);