How do you perform a 302 redirect using MVC3 and ASP.Net? - asp.net-mvc-3

I'm using Razor, HTML5, MVC3 with C# in an application, where after a user clicks on a link, I open a new window, do some processing, then want to redirect that window with a 302 status code to a link.
Thanks.

The correct way to do this in ASP.NET MVC is by having a controller action that returns a redirect ActionResult. So inside the controller action you are invoking in this window and doing the processing simply perform a redirect by returning a proper ActionResult:
public ActionResult Foo()
{
// ... some processing
return RedirectToAction("SomeAction", "SomeController");
}
When the Foo action is invoked (presumably inside the new window) it will do the processing and return a 302 HTTP status code to the client with a new location of /SomeController/SomeAction.
If you wanted to redirect to some external url of your application you could do the following:
public ActionResult Foo()
{
// ... some processing
return Redirect("http://someotherdomain.com/somescript");
}
As far as creating a link that will open in a new window/tab is concerned you could append the target="_blank" attribute on the anchor:
#Html.ActionLink(
"Some link", // linkText
"Foo", // action
"SomeController", // controller
null, // routeValues
new { target = "_blank" } // htmlAttributes
)

Related

Redirect to view with parameter doesn't work (ASP.NET Core)

I want to redirect a page with few parameters. However, if I try to do it by returning RedirectToAction(), the page will not work. Here is the code:
Controller Home, Action Display:
public IActionResult Display()
{
return RedirectToAction("Display", new
{
token = "2a4d237b-e2db-4ffe-ae42-787ae4e7566c",
id = "abcdefgh",
display = "Default"
});
}
View
<a asp-area="" asp-controller="Home" asp-action="Display">Link</a>
If I return View() in the Display() method in the Home controller, that wotks fine the page is loaded.
public IActionResult Display()
{
return View(); //this works
}
not sure what you want to achieve. If you want to redirect to an action in the same controller, you need to specify the name of your action that returns the view.
In your code above, you are redirecting to the same action. Have a look at this Answer here

Best Practice for showing Page after Post

I have a View with a Form that calls a controller action Post Method to "Complete" a Package. It then needs to refresh the page its on as that contains information that will be updated, both within the view itself and also within a partial. It does use two different Controllers in different MVC Areas.
The Post works correctly and the redirect is issued, but the page is not refreshed.
I have read that instead, I should use OnSuccess within the Ajax call that calls Complete, but I thought that was for in page calls, not ones that navigate to different pages.
View Form
#using (Ajax.BeginForm("Complete", "Packages", new { Area = "Core" },
new AjaxOptions
{
HttpMethod = "POST"
}))
{
Core(Area) Packages Controller
[HttpPost]
public ActionResult Complete(int ID)
{
// Update code
// Refresh the full page
return RedirectToAction("Summary", new { Area = "Control", id = packageBuilder.CurrentPackage.ID });
}
Control (Area) Packages Controller
[HttpGet]
public ActionResult Summary(int id)
{
// Get Model
return View("Summary", model);
}
Any pointers would be warmly welcomed.
Thanks,
Chris.
The reason that your page is not refreshed after you submit the form and the redirect is not issued in the browser, is that you are submitting the request over AJAX. This is a request issued by the browser behind the scenes.
If you want to submit the form and for the page to be refreshed, I'd recommend changing your code from Ajax.BeginForm(... to Html.BeginForm(... and then it will load the page and perform the redirect as expected.
I am not quite sure how your ajax calls are structured, but if you are using the MVC Ajax helper you can just call `location.reload(); in the OnComplete method, like so:
#using (Ajax.BeginForm(new AjaxOptions{OnComplete = "javascriptfunction"}))
{
//Data and submit button
}
<script>
function javascriptfunction(){
location.reload();
}
</script>

Redirect after AJAX form submission

Using MVC 4, I have a partial view form which contains an #Ajax.BeginForm.
The form submits as expected, and the result is displayed asynchronously in my main view.
I want a condition on my controller that if a certain parameter is true on my form, then it redirects to a whole new page (instead of displaying the result in my main view).
When I tried return RedirectToAction, the whole view displays in the div that the form normally displays in, as opposed to ignoring the AJAX and redirecting to a completely new page.
Does anyone know how I can acheive this?
You can use return JavaScript to achieve it.
public ActionResult MyAction()
{
if (parameter)
{
return JavaScript("window.location = '" + Url.Action("Action", "Controller") + "'");
}
//Do something here
return PartialView("ParitalView", Model);
}
You could not perform RedirectToAction in a ajax call.
Just return a HttpStatusCodeResult and based on it perform redirect in Javascript
public ActionResult Save()
{
return new HttpStatusCodeResult(302,
"/Users/Details");
}
In Ajax Error function, set in AjaxOptions { OnFailure = "Error" }
function Error(response, status, error) {
window.location.href= response.statusText;
}

MVC3 Dynamic Return URL

I want to have a View that has a link that will be set to the url of whatever page the user navigated to this view from.
Let's say I have a View and relative Action named InfoPage, and on this page I want a link that simply says 'Return'.
If the user is on PageA and navigates to InfoPage, clicking the 'Return' link returns the user to PageA.
If the user is on PageB and navigates to InfoPage, clicking the 'Return' link returns the user to PageB.
I'm thinking the easiest means to do this will be to add the 'ReturnUrl' as a property of the model used in InfoPage.
My question this is how do I get that return url.
public ViewResult InfoPage(){
var model = new InfoPageModel();
//Set my model's other properties here...
model.ReturnUrl = ''//Where do I get this?
return view(model);
}
And then in my view
Return
The most robust way to do this is to pass a query-string parameter to your page from the caller page. Every link to this page will be required to pass its own URL. (Request.Url).
You could also use Request.UrlReferrer in your control, but not all browsers send Referer headers.
To dynamically construct a returnUrl within any controller action:
var formCollection =
new FormCollection
{
new FormCollection(this.HttpContext.Request.Form),
new FormCollection(this.HttpContext.Request.QueryString)
};
var parameters = new RouteValueDictionary();
formCollection.AllKeys
.Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
.ForEach(p => parameters.Add(p.Key, p.Value));
var returnUrl =
this.Url.Action(
this.RouteData.Values["action"].ToString(),
this.RouteData.Values["controller"].ToString(),
parameters
);
Related: How do I redirect to the previous action in ASP.NET MVC? (Same but from within any View)

Refreshing parent view when a partial view's form is submitted

I'm looking into using partial views in MVC3 using Razor, and I get my partial view to render and it works fine.
What I'd like to do, though, is refresh the parent view when the partial view is submitted.
Code in my parent view to render partial view
<div id="mydiv">
#{ Html.RenderAction("Add", "Request"); }
</div>
Action for parent view is simple,
public ActionResult Index()
{
List<obj> reqs = //some query
return View(reqs);
}
In my partial view's get action I have:
public ActionResult Add()
{
AddRequestViewModel vm = new AddRequestViewModel();
//set some stuff on the VM here
return PartialView(vm);
}
In the post action called by the partial view, if modelstate isn't valid, return PartialView(vm)
If it is valid, I'd like the parent and partial views to refresh.
I tried RedirectToAction, but this can't be called in an action called by a partial, apparently, and I tried return Index();, but this causes an issue with the code used to render the partial view,
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List'1[DatRequests.Models.ReqRequest]', but this dictionary requires a model item of type 'DatRequests.ViewModels.AddRequestViewModel'.
Any suggestions on how to do this would be appreciated. The purpose of the page is to show a list of elements, and the partial contains a form to add a new element to the list.
Edit: The partial's model is different, as it contains data for selection, which is from a db, which is why I tried RenderAction, but I'm not sure if there are other ways of doing this.
When the partial view is submitted normally you submit it to some controller action. You could either submit it using a normal request or an AJAX request. If you use a normal request you could perform a standard redirect to the Index inside the POST controller action that will handle the form submission. If you use AJAX, you could return a JSON result pointing to the url that you want to redirect:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
return Json(new { url = Url.Action("Index") });
}
and inside your AJAX success callback:
success: function(result) {
if (result.url) {
// we have a success
window.location.href = result.url;
} else {
// invalid modelstate => refresh the partial
$('#mydiv').html(result);
}
}
Probably RenderAction should not be used this way.
When using Html.RenderAction, a new/seperate request would be sent to the server. And you got another chance to load some data from db or somewhere else to display to the client. Also, you could apply OutputCache to this action. this is usually the way doing global cache.
Here you are doing a POST to the server. Either directly put a element here or using a partial view to do the Post. And in the corresponding action, do a RedirectToAction.
Do it with ajax or not isn't the point. my opinion is more about the right way using RenderAction

Resources