I'm brand new to MVC (having done classic ASP for many years). I'm not sure I know how to ask this question. Basically, I want the actions of one controller to seamlessly transfer/redirect to another view/controller. I have tried
public class SetupController : Controller
{
...
public ActionResult Bicycles()
{
return RedirectToAction("Index", "Bicycles");
}
}
but the problem is that this takes me to localhost/Bicycles (which doesn't exist). What I want is to go to localhost/Setup/Bicycles. I tried this (adding "Setup" parent folder to controller name):
public class SetupController : Controller
{
...
public ActionResult Bicycles()
{
return RedirectToAction("Index", "Setup/Bicycles");
}
}
but this created an infinite redirect loop, which the browser rightly refused to do.
Hope it makes sense what I'm trying to do.
I believe what you are looking for is:
public ActionResult Bicycles()
{
return RedirectToAction("Bicycles", "Setup");
}
The first parameter is the Action, the second the Controller.
Since you already are in SetupController in Bicycles action, you would get an infinite redirect. However, from what you mentioned, that is where you are attempting to redirected to.
protected internal RedirectToRouteResult RedirectToAction(
string actionName,
string controllerName
)
So your first example redirects to Index action in Bicycles controller, hence the localhost/Bicycles.
Related
İn my MVC3 project, there is plenty of TempData[] that I am using for passing datas between actions. And it works totaly perfect when I use Chrome. But in IE I can't get values of TempData[] items. if anyone knows whats the problem and how can I solve it?`
public class SomeController : Controller
{
public ActionResult SomeAction()
{
TempData["id"] = "someData";
return View();
}
}
public class AnotherController : Controller
{
public ActionResult AnotherAction()
{
string data = Convert.ToString(TempData["id"]);
return View();
}
}
`
You should never return a view from a controller action that stores something into TempData. You should immediately redirect to the controller action that is supposed to use it:
public class SomeController : Controller
{
public ActionResult SomeAction()
{
TempData["id"] = "someData";
return Redirect("AnotherAction", "Another");
}
}
public class AnotherController : Controller
{
public ActionResult AnotherAction()
{
string data = Convert.ToString(TempData["id"]);
return View();
}
}
The reason for this is that TempData survives only for a single additional request. So for example if inside the view you are sending an AJAX request to some controller action (no matter which) and then have a link in this view pointing to the target action, when the user is redirected to this target action TempData will no longer exist since it was lost during the AJAX request done previously.
If you need to store data for longer than a single redirect you could use Session.
If you need to store data for longer than a single redirect you should use Keep or Peek methods.
string data = TempData["id"].;
TempData.Keep("id");
or simply use,
string data = TempData.Peek("id").ToString();
Peek function helps to read as well as advice MVC to maintain “TempData” for the subsequent request.
I have this code and I can't understand why it works this way
I have a model and view which is arbitrary and a very simple (but weird) controller
Here is my controller:
public partial class RouteController : Controller
{
[HttpGet]
public virtual ActionResult Create()
{
Create create = new Create();
return View("Create", create);
}
[HttpPost]
public virtual ActionResult Create(Create route)
{
return Create();
}
}
The first create method loads the view as normal. When the view posts back it runs the 2nd action which runs the first (as expected). The wierd part is the view is (re-)loaded with my previously entered data with errors (if any). I dont understand this because my model is empty. I was expecting it to post back with the same form as if it was loaded for the first time but with errors possibly.
Please explain.
That's the normal behavior of HTML helpers and it is by design. They first look at values contained in the ModelState and after that in the actual model. If you intend to modify some values on the model in a POST action you need to remove them from modelstate first:
For example:
[HttpPost]
public virtual ActionResult Create(Create route)
{
ModelState.Remove("SomeProperty");
route.SomeProperty = "some new value";
return View(route);
}
If you intend to completely modify everything as in your example you could clear the modelstate entirely:
[HttpPost]
public virtual ActionResult Create(Create route)
{
ModelState.Clear();
return Create();
}
Another possibility is to write your own TextBoxFor, HiddenFor, CheckBoxFor, ... helpers that will use the value in the model and not the one in the model state. Or yet another (non-recommended) possibility:
<input type="text" name="SomeProperty" value="#Model.SomeProperty" />
Of course in this case client validation among other things provided by the standard helpers won't work.
Hey guys,
What is the best mechansims for persisting viewmodel data from one controller to another.
For instance
return RedirectToAction("SomeAction", "SomeController");
I need to have some data from the previous controller available to the new controller I am redirecting to.
If you are not passing an object or something complex, make use of parameters. Just make sure redirected action gets parameters to display what it should.
return RedirectToAction("SomeAction", "SomeController",new { id=someString} );
Get the parameter in the action:
public ActionResult SomeAction(string id)
{
//do something with it
}
#Ufuk Hacıoğulları: You can't share information between 2 controllers using ViewData. ViewData only shares information between Controller and View.
If you need to share complex information between multiple Controllers while redirection, use "TempData" instead.
Here is how you use "TempData" - http://msdn.microsoft.com/en-us/library/dd394711.aspx
A redirect is going to send an http response to the client that directs it to then make a new http request to /SomeController/SomeAction. An alternative would be for you to call a method on your other controller directly... new SomeController().SomeAction(someData) for example.
I think this will be helpfull to you to pass value from one action to another action .
public ActionResult ActionName(string ToUserId)
{
ViewBag.ToUserId = ToUserId;
return View();
}
public ActionResult ssss(string ToUserId)
{
return RedirectToAction("ActionName", "ControllerName", new { id = #ToUserId });
}
Hurro.
I'm trying to achieve some conditional routing based on whether the current user is an admin or not. The system only has two modes, admin or non-admin and nothing more than this. I'm using areas for my admin area because the controller names would be the same, but they'll deliver different functionality pretty much in every case.
In this system, however, the admins shouldn't really be aware of their admin location, they just know that they use the system to do something else other than what regular users do. I don't want there to be any distinction between the two in terms of URL because of this. What I want to do is be able to do something like mysite.com/AuditHistory and dependant on whether you're an admin or user will depend on what controller is used. So if it's a user making this request, then it'd use the AuditHistoryController in the regular controllers folder, but if it's an admin then it'd use the AuditHistoryController in Areas/Admin/Controllers.
I've seen the use of IRouteConstraint and can do something along the following lines:
public class AdminRouteConstraint : IRouteConstraint
{
public AdminRouteConstraint() { }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.User.IsInRole("Admin");
}
}
With the following:
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", controller = "Home", id = UrlParameter.Optional },
new { controller = new AdminRouteConstraint() }
);
Can I simply get rid of "Admin/" at the front and do the same thing for the other routes but say UserRouteConstraint? I've not seen this done anywhere though and not sure if it's correct.
Any ideas on how to do this?
Could you simply redirect the user from the ActionResult if they are in a role? That is if you don't mind the URL changing?
Something like this...
[Authorize]
public ActionResult AuditHistory()
{
if(Context.User.IsInRole("Admin")
{
return Redirect("Admin/AuditHistory");
}
else
{
return View();
}
}
To me, this is a bit of a hack. But it may be a solution.
Obviously, you would need to do basic checks like making sure the current request is authenticated etc.
If you really don't want the URL to change, you could possibly have two separate views and do away with the admin Area
[Authorize]
public ActionResult AuditHistory()
{
if(Context.User.IsInRole("Admin")
{
return View("AdminAuditHistory", new AdminAuditHistoryViewModel());
}
else
{
return View("AuditHistory", new AuditHistoryViewModel());
}
}
In fact I think this is probably the cleanest solution, but is possibly still a bit of a hack.
I hope this helps.
We have an a PHP application that we are converting to MVC. The goal is to have the application remain identical in terms of URLs and HTML (SEO and the like + PHP site is still being worked on). We have a booking process made of 3 views and in the current PHP site, all these view post back to the same URL, sending a hidden field to differentiate which page/step in the booking process is being sent back (data between pages is stored in state as the query is built up).
To replicate this in MVC, we could have a single action method that all 3 pages post to, with a single binder that only populates a portion of the model depending on which page it was posted from, and the controller looks at the model and decides what stage is next in the booking process. Or if this is possible (and this is my question), set up a route that can read the POST parameters and based on the values of the POST parameters, route to a differen action method.
As far as i understand there is no support for this in MVC routing as it stands (but i would love to be wrong on this), so where would i need to look at extending MVC in order to support this? (i think multiple action methods is cleaner somehow).
Your help would be much appreciated.
I have come upon two solutions, one devised by someone I work with and then another more elegant solution by me!
The first solution was to specify a class that extends MVcRouteHandler for the specified route. This route handler could examine the route in Form of the HttpContext, read the Form data and then update the RouteData in the RequestContext.
MapRoute(routes,
"Book",
"{locale}/book",
new { controller = "Reservation", action = "Index" }).RouteHandler = new ReservationRouteHandler();
The ReservationRouteHandler looks like this:
public class ReservationRouteHandler: MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var request = requestContext.HttpContext.Request;
// First attempt to match one of the posted tab types
var action = ReservationNavigationHandler.GetActionFromPostData(request);
requestContext.RouteData.Values["action"] = action.ActionName;
requestContext.RouteData.Values["viewStage"] = action.ViewStage;
return base.GetHttpHandler(requestContext);
}
The NavigationHandler actually does the job of looking in the form data but you get the idea.
This solution works, however, it feels a bit clunky and from looking at the controller class you would never know this was happening and wouldn't realise why en-gb/book would point to different methods, not to mention that this doesn't really feel that reusable.
A better solution is to have overloaded methods on the controller i.e. they are all called book in this case and then define your own custome ActionMethodSelectorAttribute. This is what the HttpPost Attribute derives from.
public class FormPostFilterAttribute : ActionMethodSelectorAttribute
{
private readonly string _elementId;
private readonly string _requiredValue;
public FormPostFilterAttribute(string elementId, string requiredValue)
{
_elementId = elementId;
_requiredValue = requiredValue;
}
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (string.IsNullOrEmpty(controllerContext.HttpContext.Request.Form[_elementId]))
{
return false;
}
if (controllerContext.HttpContext.Request.Form[_elementId] != _requiredValue)
{
return false;
}
return true;
}
}
MVC calls this class when it tries to resolve the correct action method on a controller given a URL. We then declare the action methods as follows:
public ActionResult Book(HotelSummaryPostData hotelSummary)
{
return View("CustomerDetails");
}
[FormFieldFilter("stepID", "1")]
public ActionResult Book(YourDetailsPostData yourDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[FormFieldFilter("stepID", "2")]
public ActionResult Book(RoomDetailsPostData roomDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[HttpGet]
public ActionResult Book()
{
return View();
}
We have to define the hidden field stepID on the different pages so that when the forms on these pages post back to the common URL the SelectorAttributes correctly determines which action method to invoke. I was suprised that it correctly selects an action method when an identically named method exists with not attribute set, but also glad.
I haven't looked into whether you can stack these method selectors, i imagine that you can though which would make this a pretty damn cool feature in MVC.
I hope this answer is of some use to somebody other than me. :)