As I am new to ASP.NET MVC can anybody tell me the difference between return RedirectToAction() and return View()?
return View() tells MVC to generate HTML to be displayed and sends it to the browser.
RedirectToAction() tells ASP.NET MVC to respond with a Browser redirect to a different action instead of rendering HTML. The browser will receive the redirect notification and make another request for the new action.
An example ...
let's say you are building a form to collect and save data, your URL looks like SomeEntity/Edit/23. In the Edit action you will do return View() to render a form with input fields to collect the data.
For this example let's say that on successful save of the data you want to display the data that has been saved. After processing the user's submitted data, if you do something like a RedirectToAction("Index") where Index is the action that will display the data. The browser will get a HTTP 302 (temporary redirect) to go to /SomeEntity/Index/23.
Return View doesn't make a new requests, it just renders the view
without changing URLs in the browser's address bar.
Return RedirectToAction makes a new request and the URL in the browser's
address bar is updated with the generated URL by MVC.
Return Redirect also makes a new request and the URL in the browser's address
bar is updated, but you have to specify the full URL.
RedirectToRoute redirects to the specified route defined in the the
route table.
Between RedirectToAction and Redirect, best practice is to use
RedirectToAction for anything dealing with your application
actions/controllers. If you use Redirect and provide the URL, you'll
need to modify those URLs manually when you change the route table.
As an addition to all answers above, if you are using Implementing Validation using Data Annotation, use return View() instead of RedirectToAction().
Validation message will not work using RedirectToAction as it doesn't get the model that is not valid and your validation message will not show as well on your view.
here is simplest explanation of rendering view in mvc.
Related
After a user has completed a form in MVC and the post action is underway, I am trying to redirect them back to another view within another model.
Eg. This form is a sub form of a main form and once the user has complete this sub form I want them to go back to the main form.
I thought the following might have done it, but it doesn't recognize the model...
//send back to edit page of the referral
return RedirectToAction("Edit", clientViewRecord.client);
Any suggestions are more that welcome...
You can't do it the way you are doing it. You are trying to pass a complex object in the url, and that just doesn't work. The best way to do this is using route values, but that requires you to build the route values specifically. Because of all this work, and the fact that the route values will be shown on the URL, you probably want this to be as simple a concise as possible. I suggest only passing the ID to the object, which you would then use to look up the object in the target action method.
For instance:
return RedirectToAction("Edit", new {id = clientViewRecord.client.ClientId});
The above assumes you at using standard MVC routing that takes an id parameter. and that client is a complex object and not just the id, in which case you'd just use id = clientViewRecord.client
A redirect is actually just a simple response. It has a status code (302 or 307 typically) and a Location response header that includes the URL you want to redirect to. Once the client receives this response, they will typically, then, request that URL via GET. Importantly, that's a brand new request, and the client will not include any data with it other than things that typically go along for the ride by default, like cookies.
Long and short, you cannot redirect with a "payload". That's just not how HTTP works. If you need the data after the redirect, you must persist it in some way, whether that be in a database or in the user's session.
If your intending to redirect to an action with the model. I could suggest using the tempdata to pass the model to the action method.
TempData["client"] = clientViewRecord.client;
return RedirectToAction("Edit");
public ActionResult Edit ()
{
if (TempData["client"] != null)
{
var client= TempData["client"] as Client ;
//to do...
}
}
ASP MVC WebGrid renders pagination links like
http://host/AnyController/AnyAction?Length=4&page=1
Any chance to parametrize or customize this to
http://host/AnyController/AnyAction/1
to conform better to MVC routing conventions?
(NOT important: btw Length is redundant. If the controller's Action method does not know the page length, by heart that's problem. )
Thanks in advance
One way to handle your default route conflict can be this, as most of the time when you use you route it will hit the action method without the [HttpGet]. All you need to do is a GET, whenever you sort or page the web gird, it will try to get data and hit the a HttpGet Action, this will work as follows:
[HttpGet]
public ActionResult YourActionMethod()
{
return PartialView("YourView",YourModel);
}
The best part is, upon sorting, the request will send a parameter named as "sortBy" too, you can use this here and decide what you want to do with the binded Model with the grid. You can inspect what URL the Sort header will hit by using the "Developer Tools" in your browser. You can use this action do as you will,
Note : By default the action method it would be hitting would be same as the controller name.
I'm sorry to ask such a basic question, but it's kind of fundamental for me. To better understand filters, I need to understand this notions. Although I'm on ASP.NET MVC for few months now and now are doing nice demos, I'm more familiar with Action method concept than action result.
What are:
Action Method?
Action Result?
How are they related?
Let's say I've this
public ViewResult ShowPerson(int id)
{
var friend = db.Persons.Where(p => P.PersonID == id).First();
return View(friend);
}
How those concepts apply to the above code?
Thanks for helping.
In your example ShowPerson is the action. Each action needs to return an action result (In your case it returns a view). So when a controller action method is invoked it does some processing and decides what view would be best adapted to represent the model.
There are many different action results that you might use. They all derive from ActionResult:
ViewResult - if you want to return a View
FileResult - if you want to download a file
JsonResult - if you want to serialize some model into JSON
ContentResult - if you want to return plain text
RedirectResult - if you want to redirect to some other action
HttpUnauthorizedResult - if you want to indicate that the user is not authorized to access this action
FooBarResult - a custom action result that you wrote
Answer by #Darin-dimitrov is very much upto the point. But I see explanation given on MSDN also very much helpful.
Action methods typically have a one-to-one mapping with user
interactions. Examples of user interactions include entering a URL
into the browser, clicking a link, and submitting a form. Each of
these user interactions causes a request to be sent to the server. In
each case, the URL of the request includes information that the MVC
framework uses to invoke an action method.
When a user enters a URL into the browser, the MVC application uses
routing rules that are defined in the Global.asax file to parse the
URL and to determine the path of the controller. The controller then
determines the appropriate action method to handle the request. By
default, the URL of a request is treated as a sub-path that includes
the controller name followed by the action name. For example, if a
user enters the URL http://contoso.com/MyWebSite/Products/Categories,
the sub-path is /Products/Categories. The default routing rule treats
"Products" as the prefix name of the controller, which must end with
"Controller" (such as ProductsController). It treats "Categories" as
the name of the action. Therefore, the routing rule invokes the
Categories method of the Products controller in order to process the
request. If the URL ends with /Products/Detail/5, the default routing
rule treats "Detail" as the name of the action, and the Detail method
of the Products controller is invoked to process the request. By
default, the value "5" in the URL will be passed to the Detail method
as a parameter.
I have a ActionLink, that calls my public ActionResult, and I would like it to return back to the page that it was called from, but how?
There are a couple of tricks that you can use for this.
The simplest is ...
return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
AbsoluteUri may not give you the exact path you are looking for, but UrlReferrer should have the imformation you are looking for. Redirect returns a subclass of ActionResult so it is a valid return value.
Another idea is to base the redirect location off of stored values. This is useful when you are going to make multiple requests before you want to redirect, such as when you validate a form and show validation issues on the first response. Another situation will be when the referrer is not a local site. In either case, your referrer won't be what you want it to and you will need to retrieve the correct location from somewhere else.
Specific implementations include using a hidden input field on your form, session state, pulling a descriminator value from your route data, or even just a more constant value like HttpContext.Request.ApplicationPath.
Good luck.
Keep in mind that due to the state-less nature of the web, your ActionResult isn't "called from" your ActionLink as much it is simply a url that the user-agent requested.
Because of this, the only real "built-in" way you can know where that user was coming from is by inspecting the http Request headers to see what the referring page was:
string referrer = Request.Headers["referer"];
You'd then be responsible for parsing out the Action method from this url, if you were going to call it directly. Be aware that this referrer may not be a link within your own site.
I have the following scenario:
I have an edit page, which can be called from different pages. These pages could be the detail view for the current entity, or the list view for the entities (with or without a search in the route).
HOW do I cleanly redirect to the original calling page using the MVC framework? Of course I could simply pass the HttpContext.Request.Url value by holding it in my TempData, but that sort of smells, in my eyes (or, err, nose). It's on a lower level than the rest of the code.
Is there a way to get the routevalues for the previous page in a controller context? If I have that, I could store that temporarily and pass that to the redirect.
Do not use TempData when not redirecting. One AJAX request from your edit page, and the TempData will go away.
Tomas is right that a hidden element or query string parameter is the way to go. But make sure you sanitize the value submitted. You don't want to redirect any old site on the web; you need to ensure that the page to which you redirect is part of your sites.
you can always have a hidden form element telling the controller where to redirect when posting a form. when using a get request, you could use a querystring in a similar way. it might not be the most beautiful solution, but it's quite a lot safer than trusting httpreferrer or other headers that could easily be changed (or ommitted) by the browser.