繁体   English   中英

在ASP.NET MVC中使用重定向传递复杂对象?

[英]Pass complex object with redirect in ASP.NET MVC?

嗨,

我有一个看起来像这样的动作:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(AdRegister adRegister, IEnumerable<HttpPostedFileBase> files)

AdRegister是一个复杂的类,我需要将其传递给Register操作中的一个重定向方法,如下所示:

return this.RedirectToAction("Validate", adRegister);

Validate操作如下所示:

public ActionResult Validate(AdRegister adRegister)

我知道我可以传递简单的参数但在这种情况下它是一个复杂的对象。 此示例不起作用,adRegister的属性将为null。

这是可能的,如果是这样,怎么样?

最好的祝福

更多信息:注册操作将采用adRegister并对其执行魔术,然后将其发送到Validate操作。 Validate操作将向用户返回验证页面。 当用户点击授权按钮时,adRgister将从表单中填充,然后发送到vValidate帖子,在该帖子中将保存。 我已经查看过将adRegister暂时放在缓存或数据库中,但如果我可以简单地将其传递给下一个操作,那就更好了。

一种可能性是在查询字符串中传递简单属性:

return RedirectToAction(
    "Validate", 
    new { 
        foo = adRegister.Foo, 
        bar = adRegister.Bar, 
        ... and so on for all the properties you want to send
    }
);

另一种可能性是将它存储在TempData(重定向的生命周期)或Session(ASP.NET会话的生命周期)中:

TempData["adRegister"] = adRegister;
return RedirectToAction("Validate");

然后从TempData中检索它:

public ActionResult Validate()
{
    adRegister = TempData["adRegister"] as AdRegister;
    ...
}

另一种可能性(也是我建议您使用的那种)是将此对象保留在数据存储区的POST方法中:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(AdRegister adRegister, IEnumerable<HttpPostedFileBase> files)
{
    ...
    string id = Repository.Save(adRegister);
    return RedirectToAction("Validate", new { id = adRegister.Id });
}

然后在重定向后从数据存储中获取它:

public ActionResult Validate(string id)
{
    AdRegister adRegister = Repository.Get(id);
    ...
}

一个想法可能会创建一个会话变量并传递一个引用该会话变量的Key,如果该对象需要一些视图?

ASP.NET MVC的tempdata应该是完美的。

也就是说,TempData或Session是一个选项,但有一些缺点,如相当违反,往往是模糊或难以调试。 可能更可取的是“暂存”持久性存储中的临时值,例如用户的配置文件或您自己的数据库,然后通过validate方法传递密钥,然后可以从所述存储加载数据。 这也开辟了恢复废弃车等的可能性。

暂无
暂无

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

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