Show querystring after POST - asp.net-mvc

I'm using MVC4/Razor. After a GET request the view shows the querystring, and after a POST request the view does not show the querystring - both as expected.
But, I have an action with [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)], and I need to POST a form to it, and to show the corresponding querystring.
How can I do this on the server side? I know this can be done on the client side by converting to a GET request, and I am curious to see how to do that, but only if that is the only way to make this work.

You can return RedirectToAction with posted parameters
return RedirectToAction("About", "Create",
new { id = PId, Name=PName }); // more params if needed
The parameters will be included in the querystring.

Related

MVC Redirect to a different view in another controller

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...
}
}

Previous GET parameters being unintentionally preserved in POST request

As of current I navigate to a view using a GET request, looking something like this:
/batches/install?Id=2&ScheduledDate=07.29%3A12
From there, I send a POST request using a form (where I include what data I wish to include in the request.
Furthermore I set the forms action to "Create" which is the action I wish to send the request to.
My issue is the fact that sending this request keeps the GET arguments in the POST url, making it look the following:
../batches/Create/2?ScheduledDate=07.29%3A12
I do not want this since:
1: it looks weird
2: it sends data I do not intend it to send in this request
3: if my model already has a property named "id" or "scheduledDate" the unintentional GET parameters will get bound to those properties.
How can I ignore the current GET parameters in my new POST request?
I just want to send the form POST data to the url:
../batches/create
(without any GET parameters)
How would this be done?
As requested, here is my POST form:
#using (var f = Html.Bootstrap().Begin(new Form("Create")))
{
//inputs omitted for brevity
#Html.Bootstrap().SubmitButton().Style(ButtonStyle.Success).Text("Create batch")
}
Note that I use the TwitterBootstrapMVC html helpers (https://www.twitterbootstrapmvc.com/), althought this really shouldn't matter.
As requested, to sum up:
I send a get request to : /batches/install?Id=2&ScheduledDate=07.29%3A12.
Through the returned view I send a POST request to: /batches/create.
However the previous get parameters get included in the POST request URL making the POST request query: /batches/Create/2?ScheduledDate=07.29%3A12 (which is NOT intended).
This is not a great Idea though, but will give you what you want.
[HttpPost]
public ActionResult Create() {
//do whatever you want with the values
return RedirectToAction("Create", "batches");
}
This is a "Feature" of MVC that was previously reported as a bug (issue 1346). As pointed out in the post, there are a few different workarounds for it:
Use named routes to ensure that only the route you want will get used to generate the URL (this is often a good practice, though it won't help in this particular scenario)
Specify all route parameters explicitly - even the values that you want to be empty. That is one way to solve this particular problem.
Instead of using Routing to generate the URLs, you can use Razor's ~/ syntax or call Url.Content("~/someurl") to ensure that no extra (or unexpected) processing will happen to the URL you're trying to generate.
For this particular scenario, you could just explicitly declare the parameters with an empty string inside of the Form.
#using (var f = Html.Bootstrap().Begin(new Form("Create").RouteValues(new { Id = "", ScheduledDate = "" })))
{
//inputs omitted for brevity
#Html.Bootstrap().SubmitButton().Style(ButtonStyle.Success).Text("Create batch")
}

Difference between redirectToAction() and View()

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.

WebResponse to HttpResponseBase. Is it possible?

In a controller action, I am manually sending a form to a remote URL using WebRequest. I successfully receive a WebResponse containing an html page to display. I would like to "paste" this response as the Response (of type HttpResponseBase) of the action. An action normally returns an ActionResult, so how do I conclude my controller action so that the WebResponse will be the result?
Note: the Url in the browser must also become the url of the response.
Update: Here is the goal. This is on a paypal checkout page. Instead of having a form with all cart hidden fields and a checkout submit button in my view, I would like a simple checkout button linked to one of my actions. In this action, I will prepare the WebRequest with the form and send it to paypal. Doing this in an action also allows me to store the inactivated order in a DB table so that when the order confirmation comes I can compare it with the stored order and activate it.
Solution: thanks to those who answered for pointing out that this would not be possible to redirect with a POST. It appears that I am not obliged to redirect to paypal with a POST. Instead I can construct a URL with all the cart data in the query string and redirect to it. Doing it from a controller action method still allows me to store the pending order in a database.
Thanks
If you just want the content of the WebRequest response to be sent back in the response from your controller action, you could do something like this in your action method:
WebRequest req = WebRequest.Create("http://www.google.com");
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
ContentResult cr = new ContentResult();
cr.Content = sr.ReadToEnd();
return cr;
this is even more concise:
WebRequest req = WebRequest.Create("http://www.google.com");
WebResponse res = req.GetResponse();
FileStreamResult fsr = new FileStreamResult(res.GetResponseStream(),res.ContentType);
return fsr;
THere is no direct way to do this. I dont know much about ASp.NET. ARe you saying that your ASP.net page is doing a HTTP request to a remote site, and getting back a response, and you want that response to become a HTTPResponseBase? What do you want to do with it after that?
See the following SO thread on a similar topic...
How do I mock HttpResponseBase.End()?

Redirect problem

I have this code in the client side:
$.post('<%=Url.Action("Action_Name","Controller_Name")%>', { serverParam: clientParam}, null, null);
And this code in the server side:
[HttpPost]
public ActionResult Action_Name(string serverParam)
{
return View();
}
I currently am in a view and when i click a button i want to be redirected to Controller_Name/Action_Name/serverParam.
After the post i am sent in the action method but i still see the old view, not Action_Name
(Action_Name.aspx exists)
(I am using mvc 2)
First, you should follow the "Post/Redirect/Get" pattern by returning a redirect result instead of a view after a successful post. But that would not solve the problem you're actually asking about.
This is doing an AJAX POST, not a "regular" POST. So the browser isn't going to honor a redirect response by redirecting. You could "redirect" in your response callback by setting window.location, but...
The easiest way to do what you want is to just post the form, rather than using $.post, which is a shortcut to $.ajax, like this:
$("#someForm").submit();

Resources