【问题标题】:Passing ViewModel Object From ActionMethod to Another将 ViewModel 对象从 ActionMethod 传递给另一个
【发布时间】:2011-05-01 14:16:01
【问题描述】:

我的 Web 应用程序的侧栏中有一个注册表单。当用户提交输入的数据时,当用户可以填写其余数据时,应将用户重定向到具有更完整注册表单的另一个页面。用户在第一种形式中输入的数据应该已经存在于第二种形式中,但这并没有发生……我检查了我传递给第二个操作方法的视图模型的值,它是null 并且在浏览器的地址栏中我得到:

http://localhost:2732/User/RegisterPage?model=Sharwe.MVC.ViewModels.RegisterPageViewModel

代码如下:

    public ActionResult Register()
    {
        return PartialView(new RegisterViewModel());
    }

    [HttpPost]
    public ActionResult Register(RegisterViewModel dto)
    {
        var model = Mapper.Map<RegisterViewModel, RegisterPageViewModel>(dto);
        return RedirectToAction("RegisterPage", "User", new { viewModel = model });
    }

    public ActionResult RegisterPage(RegisterPageViewModel viewModel)
    {
        return View(viewModel);
    }

这不就是这样做的吗?还是我在这里遗漏了什么……?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 routing viewmodel


    【解决方案1】:

    传递给 RedirectToAction() 的字典是路由值而不是视图模型。而 RedirectToAction() 基本上是告诉浏览器转到某个 URL。浏览器默认发出 GET 请求,显然您会丢失数据。

    为此,您需要使用 TempData 字典。您可以将视图模型存储在 TempData 中,然后将 RedirectToAction() 存储到 RegisterPage。 TempData 仅保存 1 个请求跨度的数据,并会自动将其删除。它非常适合这种情况。

    更多详情请看这里>The value for a object inside a viewmodel lost on redirect to action in asp.net mvc 2.0?

    【讨论】:

    • 啊,我明白了。那么如何从 TempData 获取数据,我是手动进行(即:对于每个字段)还是可以通过模型绑定来为我做呢?而且由于 TempData 是某种形式的 Session,如果我还没有解决这个问题,你真的认为它会起作用吗:stackoverflow.com/questions/5844635/…
    • 工作就像一个魅力!谢谢你:)
    【解决方案2】:

    在这种特殊情况下,您不需要使用RedirectToAction,您可以直接调用RegisterPage 操作:

    [HttpPost]
    public ActionResult Register(RegisterViewModel dto)
    {
        var model = Mapper.Map<RegisterViewModel, RegisterPageViewModel>(dto);
        return RegisterPage(model);
    }
    
    public ActionResult RegisterPage(RegisterPageViewModel viewModel)
    {
        return View(viewModel);
    }
    

    【讨论】:

    • @ataddeini:没用...抱怨 ViewModel 类型,它并没有真正进入预期的“页面”。
    • @Kassem:好的,不知道为什么它会抱怨 ViewModel 类型。我猜这是运行时错误吗?
    • @Kassem:好的,好的,重新阅读您的场景,像 nEEbz 建议的那样使用 TempData 确实更有意义。
    • @Kassem:短注册表和长注册表中的字段名称是否相同?可能是它没有正确绑定模型,因为字段名称不匹配(或类似的东西)。
    • @Kassem:@model 指令在RegisterPage 视图上是什么样的?如果未设置为使用RegisterPageViewModel,那么无论如何您都可能会收到类型错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多