简体   繁体   English

MVC将复杂对象传递给行动

[英]MVC passing complex object to action

I have two actions in my controller when a user call one i need to redirect it to another one and pass a complex object : 当用户调用一个控制器时,我需要在控制器中执行两个操作,我需要将其重定向到另一个控制器并传递一个复杂的对象:

first action : 第一步:

public virtual ActionResult Index(string Id) {
            var input = new CustomInput();
            input.PaymentTypeId = Id;
            return RedirectToAction(MVC.Ops.SPS.Actions.Test(input));
        }

second action : 第二动作:

public virtual ActionResult Test(CustomInput input) {
            return View();
        }

The probelm is that the input arrives null at the second action. 问题是输入在第二个动作处为空。 how can i solve it? 我该如何解决?

You can solve this using temp data to temporarily hold a value from which the second method retrieves that value. 您可以使用临时数据解决该问题,以临时保存一个值,第二种方法从该值中检索该值。

public virtual ActionResult Index(string Id) 
{
    var input = new CustomInput();
    input.PaymentTypeId = Id;
    TempData["TheCustomData"] = input; //temp data, this only sticks around for one "postback"
    return RedirectToAction(MVC.Ops.SPS.Actions.Test());
}


public virtual ActionResult Test()
{
        CustomInput = TempData["TheCustomData"] as CustomInput;
        //now do what you want with Custom Input
         return View();

}

You can keep your tempData going so long as it is never null using the .keep() method like this, 您可以使用.keep()方法保持tempData一直持续到只要它永远不会为空,

    if (TempData["TheCustomData"] != null)
        TempData.Keep("TheCustomData");

I want to make sure that you know that RedirectToAction creates new HTTP request so this create another GET and all you can pass is RouteValueDictionary object which is like having query string parameters which is list of key and value pairs of string. 我想确保您知道RedirectToAction创建了新的HTTP请求,因此创建了另一个GET,您可以传递的只是RouteValueDictionary对象,就像具有查询字符串参数(它是字符串的键和值对的列表)一样。 That said, You can't pass complex object with your way of code however the TempData solution mentioned by @kyleT will work. 就是说,您无法通过代码方式传递复杂的对象,但是TempData提到的TempData解决方案将起作用。

My recommendation based on your code is to avoid having two actions and redirect from one another unless you are doing something more than what you have mentioned in your question. 根据您的代码,我的建议是避免执行两个操作并相互重定向,除非您做的事情超出了您在问题中提到的范围。 Or you can make your Test action accepting the id parameter the your Index action will contain only RedirectToAction passing the id as route parameter. 或者,您可以使Test动作接受id参数,那么Index动作将仅包含将id作为路由参数传递的RedirectToAction

Edit: Also, If you have no primitive properties you can pass your object like the following (Thanks to @Stephen Muecke) 编辑:另外,如果您没有原始属性,则可以像下面那样传递对象(感谢@Stephen Muecke)

return RedirectToAction("Test",(input);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM