Redirect problem - asp.net-mvc

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();

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

Redirect 301 to another action

I have an ASP.NET MVC Action:
public virtual ActionResult Show(Int32 id, String slug) {
} // Show
How can I, inside Show, redirect to another action?
I need to fire the 301 redirect HTTP Error to inform that the old url should be replaced by the new url.
How can I do this?
Thank You,
Miguel
You can use RedirectToActionPermanent.
That said, it is important to know that a response status 301 will make browsers to never ask for the original location again. For a simple redirection (302) use RedirectToAction.
Both methods are used basically in the same way. In this StackOVerflow answer there are some excellent examples.

New to MVC, am I the only one getting screwed by this common scenario

Heres the scenario - using asp.net MVC with jquery mobile - newbie on both
Problem: Back button sends a GET to a page that was created with a POST
Scenario:
Page 1 has a searchbox and submit button - clck submit does POST to page 2.
Page 2 has list of serch result links, click a search result, go to page 3
Click back button on page 3, and it sends a GET to page 2.
Tried on Safari and Firefox. Firebug showing a GET on the back button.
Is this common? How would you deal with this?
A) When submitting form, somehow add the textbox to the URL (sounds tricky)
B) Mark the search page action with both HTTPPost and HTTPGet? Then save the search text in a session or somewhere?
C) Is there a better option?
Any advice appreciated!
I think may have approached this the wrong way. In general, POST should be used for requests that potentially modify state (update database etc) on the server, and GET should be used for read-only operations.
In this case it is a read only action therefore a HTTP Get is the correct http verb to use. Assuming you are using Razor your form action would look like
#using(Html.BeginForm("Index", "Search", FormMethod.Get))
//generates an url like /search?q=searchterm
It sounds like you want page 1 and page 2 to have the same url and essentially 'post-back' to the first page, such that if you go backwards you get back to the first original non-posted page.
You can achieve this by using the [HttpPost] and [HttpGet] attributes
In your Controller you can have this
[HttpGet]
public ActionResult Search()
{
//action result get code
}
[HttpPost]
public ActionResult Search()
{
//your result post code here
}

How can I make an MVC POST return me to the previous page?

I have the following action which is called from a screen with a list of records.
[HttpPost]
//[Authorize(Roles = "admin")]
public ActionResult Edit(EditViewModel itemView)
{
Once the action has completed I would like to return to the page where the action was called from. However I don't want to refresh that page. I just want to go back to the populated screen using something similar to the "Previous" button in the browser. Right now when I click "save" my action does the following which is not what I want:
return RedirectToAction("Index");
Is there some way to Redirect to previous page with MVC3?
Something like the Stackoverflow functionality after I click edit to edit an answer where it returns to the post.
Instead of a redirection,
[HttpGet]
public ActionResult Index()
{
/// preform any processing necessary for your index page on GET
return View("Index");
}
[HttpPost]
public ActionResuit Edit(EditViewModel itemView)
{
if (ModelState.IsValid)
{
/// do whatever you want with your model...
}
// return the contents as they'd be rendered by the Index action
return Index();
}
Note that with this method the URL in the browser will still display the Edit url (like /area_name/edit), but you can fix that by:
Using a redirect (which you've said you don't want to do)
Using JavaScript to update the URL, or use history.back() as #AlanStephens suggested
Probably other methods that don't immediately come to mind.
However, I'd question whether this is really the best approach. Typically, users expect different URLs to do different things.
Or, if I understand you correctly and the edit action is being called from the Index page,
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost] /// from a form on Index
public ActionResult Index(EditViewModel model)
{
if (ModelState.IsValid)
{
////
}
return View();
}
and just take the /Edit out of play entirely. Again, I don't really care for this approach.
Based off the code you've given, it looks like you've got a paginated screen, with the ability to click edit on each row. Here's how I've solved this problem in the past.
On the Index page, when the page loads, whether it be from the main index or a paging method, add the following:
Session["CurrentUrl"] = Request.Url.ToString();
So now, at the end of the POST method for your edit page, do:
return Session["CurrentUrl"] == null ?
Index() :
Redirect(Session["CurrentUrl"]);
What you described is easily achieved using ajax calls. That way you perform whatever action you like and afterwards (on successful response), you can easily navigate from the current page, using javascript.
If you POST to a page and in response you return the same view you receive with a GET request (index page), then some users might hit F5 to reload that index page and get a warning in the browser, which actually says it will send the POST request again. This is pretty confusing for users and not really user friendly (not to mention numerous concerns related to idem-potency of it).
Although you don't like the redirect approach, because of the additional response, I guess, I should say that, in MVC, this is the correct way to do it, assuming you don't want to use ajax calls.

RedirectToAction and partial views

I'm curious why it's made exactly like that?
If i call this through AJAX:
public ActionResult Foo(){
return RedirectToAction("SomethingThatReturnsPartialView","Bar");
}
It won't return me partial view in AJAX callback but will redirect to url that represents action.
So - why it is so? What are possible workarounds?
Because when the browser receives the reply from the server that is a HTTP 30x redirect, it will do just that, regardless of how the request was initiated, either synchronously or asynchronously.
On of the possible workarounds could be something like RenderViewToString, but as we know MVC lacks this feature yet. It's a known missing feature everyone wants to get.
Look in this discussion: Render a view as a string
And also look here, there may be an option to prevent the browser going redirect with JavaScript: Catching 302 FOUND in JavaScript

Resources