Pass information back to the view when using Redirect() - asp.net-mvc

I am calling a controller from more than one page and am using a returnUrl parameter to return the correct calling location:
public ActionResult EmailOrder(int id, string returnUrl)
{
var message = "The order has been emailed";
if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
return RedirectToAction("Details", new { id, message });
}
How can I pass additional information back to the view when using Redirect(url)? In the above example, I want to be able to pass message back when returnUrl has a value.

If you are redirecting to another action method and you want to pass data that can be access in the new action method, you should use the ASP.MVC Controller TempData property. You use this as follows:
[HttpPost]
public ActionResult MyActionMethod(Order order)
{
// write your logic here to save the Order
TempData["message"] = "here is some message";
return RedirectToAction("Index");
}
Data in the TempData member will be preserved across a redirection. It will be accessible in the redirected page, and then will be removed. Once you read an entry in TempData, it will be marked for deletion.
public ActionResult RedirectedMethod()
{
//Retrieve data from TempData. It will then be marked for deletion
var data = TempData["message"].ToString();
}
If you want to get a value without marking it for deletion, you can use the "Peek" method:
var data = TempData.Peek("message")
Also, you can manually preserve a value that would otherwise be deleted by using the "Keep" method:
TempData.Keep("message")
TempData is of type TempDataDictionary.
Note that TempData uses ASP.Net Session state behind the scenes, so you must have session state turned on if you are using TempData.
For more information on TempData, see here.

Related

Redirect IGrouping<string, model> List to another action in Same Controller

return RedirectToAction("ActionName", new { lst = finalData });
[HttpGet]
Public ActionResult AcionName(IGrouping<string, ModelName> lst)
{
return View("ActionName", lst);
}
i use this code to redirect my list to another action but this is not working.
You can assign the finalData to a Session or TempData variable.
TempData["FinalData "] = finalData;
return RedirectToAction("ActionName");
From this answer: "TempData Allows you to store data that will survive for a redirect. Internally it uses the Session, it's just that after the redirect is made the data is automatically evicted"
Then in your GET Action Method,
Public ActionResult AcionName()
{
var finalData = TempData["FinalData"] as IGrouping<string, ModelName>;
return View("ActionName", finalData);
}
The problem is, if you were to refresh after the redirect, then finalData would be null. So, in that case you use Session["FinalData"] or get the data from the Database in your Get method again. You can go through the answer I have linked for disadvantages of using TempData.

MVC 5 - RedirectToAction - Cannot pass parameter correctly

I have a method that looks as follows:
[Authorize]
public ActionResult Create(int? birdRowId, Entities.BirdSighting sighting)
{
...
...
}
I want to call the above method from another method in the same controller as follows:
[Authorize]
[HttpPost]
public ActionResult Create(Entities.BirdSighting birdSighting, FormCollection collection)
{
...
...
return RedirectToAction("Create", new {birdRowId = 10, sighting = birdSighting});
}
The RedirectToAction method calls the method correctly. And, the first parameter of the method being called (birdRowId) does equal 10. However, the second parameter, sighting, is always null, even though I'm passing an instantiated object with values. What am I doing wrong?
Remember, HTTP is stateless !
RedirectToAction method returns a 302 response to the client browser and thus the browser will make a new GET request to the specified URL.
If you are trying to follow the PRG pattern, I think you should not try to pass complex objects. You should only pass the ID of the resource so that the GET action can build the resource( the model) again using that ID.
return RedirectToAction("Created", "YourControllerName", new { #id=10} );
and in the Created action, read the id and build the object there.
public ActionResult Created(int id)
{
BirdSighting sighting=GetSightingFromIDFromSomeWhere(id);
// to do :Return something back here (View /JSON etc..)
}
If you really want to pass some data across (Stateless) HTTP Requests, you may use some temporary storage mechanism like TempData
Set your object to TempData in your HttpPost action method.
[HttpPost]
public ActionResult Create(BirdSighting birdSighting, FormCollection collection)
{
// do something useful here
TempData["BirdSighting"] =birdSighting;
return RedirectToAction("Created", "YourControllerName");
}
And in your GET action method,
public ActionResult Created()
{
var model=TempData["BirdSighting"] as BirdSighting;
if(model!=null)
{
//return something
}
return View("NotFound");
}
TempData uses Session object behind the scene to store the data. But once the data is read, the data is terminated.

How to add a query string from surface controller in umbraco mvc in order to persist model values

How to add a query string from surface controller in umbraco mvc . This is my current code.
Initially I wrote a code like
public ActionResult Registration(RegisterModel model)
{
//Code to insert register details
ViewBag.Success="Registered Successfully"
return CurrentUmbracoPage();
}
with this I could successful persist my ViewBag and model properties value but I could not add a query string with it.
For certain requirement I have to change the code that returns a url with querystring.
which I did as below
public ActionResult Registration(RegisterModel model)
{
//Code to insert register details
ViewBag.Success="Registered Successfully"
pageToRedirect = AppendQueryString("success");
return new RedirectResult(pageToRedirect);
}
public string AppendQueryString(string queryparam)
{
var pageToRedirect = new DynamicNode(Node.getCurrentNodeId()).Url;
pageToRedirect += "?reg=" + queryparam;
return pageToRedirect;
}
and with this my values of the properties in model could not persist and the ViewBag returned with null value.
Can any one suggest me how to add query string by persisting the values in the model and ViewBag.
Data in ViewBag will not be available on the View when it redirects. Hence you have to add message in TempData which will be available in the View after the redirect like TempData.Add("CustomMessage", "message");

How to pass thw Viewdata to all the views in my controller?

i have a dropdown list which select a value
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Screenname(FormCollection collection)
{
Viewdata["screenname"] = collection[0];
return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
}
then i want to access this ViewData in other actions like this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection, string screenname)
{
try
{
/// thats my dataobject which creates
DataObj.SaveData(Guid.Empty, collection, screenname);
return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
}
catch
{
return View("Error");
}
}
where index looks like this ...
public ActionResult Index(string ScreenName)
{
///thats my list
GetTable = new GetDataTable(ScreenName);
return View(GetTable);
}
First when i select the value and index gets executed properly.... but when i try to access the viewdata again it doesn't contain the value so anybody if please can help ...
or alternate method to save and retrieve data .
The ViewData object is specific for the particular action that is executing. To pass data between actions, use TempData. more on the difference between the two on MSDN.
You can also directly write to the session state through the Controller.Session property.
This has actually been covered quite often here. The solution for now is to use TempData to save the data you need before you use RedirectToAction().
If you do a search for "RedirectToAction" you'll find a number of posts covering this topic, such as this one.
The next official release of the framework will fix this.
I used a view to take the data from the user and then saved it to a static variable and then used this variable to pass the data to all the other views .
Thanks anyways

Can't pass viewmodel to new action by RedirectToAction

I have a form, when user submit the form, I want to direct the user the new view to display the submitted result(transfer viewmode data to display view).
public class HomeController : Controller
{
private MyViewModel _vm;
.....
// POST: /Home/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyViewModel vm){
//.....
//set up vm to temp data _vm
_vm = vm;
return RedirectToAction("DisplayData");
}
// GET: /Home/DisplayData
public ActionResult DisplayData()
{
//get temp data for display
return View(_vm);
}
}
When I posted the form, I can create vm and put it to temp data place _vm. But this _vm can be sent to another action DisplayData, it's null in action DisplayData(). It seems that when redirect action even in same controller, _vm is lost although it is Controller var, not action method var.
How to resolve this problem?
It creates a new instance of the controller as it is a new request therefore as you have found it will be null.
You could use TempData to store the vm, TempData persists the data for 1 request only
Good explanation here
One good way is to call
return DisplayData(_vm)
instead of
RedirectToAction("DisplayData")
DisplayData should accept a model anyway.

Resources