How can I use RedirectToAction to pass an object t

2019-09-09 17:25发布

问题:

I have this scenario.

A form (ForexPayment) is filled by a user, he/she then clicks Next.

I then show new page (ForexPaymentConfirmation) with just the labels and values (i.e. a read-only confirmation page) so he/she can either Submit or Cancel the request.

My questions:

  • How do i use return RedirectToAction("ForexPaymentConfirmation"); to pass an object containing the Payment Information from one view to the next?

  • One option would be to store the Payment Information in the Current Session and reclaim it on the new page ...

  • Is there a better way of achieving this?

Searching through SO, I found this: https://stackoverflow.com/a/7599952/44080 which states:

You are actually trying to use controllers to do data access.

But in this case, I have not saved the payment yet, I need to preview on a different View, before saving.

With WebForms, i'd simply unhide a panel on the same page to achieve this.

回答1:

It is possible to pass a simple object to a GET method using

return RedirectToAction("ForexPaymentConfirmation", model);

However, internally this creates an ugly query string including all the names and values of your properties

../ForexPaymentConfirmation?somePropertyName=someValue&anotherPropertyName=AnotherValue.....

It will only work if your model contains properties which are value types (int, bool DateTime etc) or string. If any properties are complex objects or collections, binding will fail. In addition you could easily exceed the query string limit and throw and exception.

Its unclear why you need this pattern (as opposed to saving the model and then in the 'details' view having a 'delete' button' in case the user changes their mind), but you need to persist the model somewhere. You can use Session (but you should not use TempData), but its always better to persist it to some form of repository, for example to a database (could be another 'temporary' table) or serialize it to an xml file so that you can retrieve it in the GET method. Another option would be to store it in the permanent table but include a bit flag (say bool IsPending) that you could set when you 'Confirm', and in the case of 'Cancel', just delete the table row.



回答2:

There is an overload of RedirectToAction method.

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    object routeValues
)

How about passing your object as routeValue?

return RedirectToAction("MyAction", "MyController", new RouteValueDictionary(paymentInfo)

and using it in your action like

public ActionResult SearchJob(PaymentInfopaymentInfo)
{
     Return View();
}

Or you can also use TempData["paymentInfo"] to pass data from controller to controller.

As Stephen suggested. Read data using Keep() if you are using TempData to persist it's value for next request. Or your can use Session and nullify it when data is no longer needed.