【问题标题】:Transfering by calling Action method directly?直接调用Action方法传输?
【发布时间】:2013-09-22 18:24:21
【问题描述】:

我的控制器是:

public ActionResult Action1(Action1Model model)
{
   .....
   if (...)
      return Action2(new Action2Model() { .... } );  //**
   else
      return View(model);
}

public ActionResult Action2(Action2Model model)
{ ... }

基本上,在 Action1 中的某些条件下,我想将处理转移到 Action2。上面的代码给了我一个错误:The model item passed into the dictionary is of type 'Action2Model', but this dictionary requires a model item of type 'Action1Model'.

我可以在 ** 行使用它:

return RedirectToAction("Action2", new { parm1 = ..., parm2 = ... ...});

但是这种方法返回 302(额外的 Http 调用),暴露了查询字符串上的所有参数,不能有复杂的模型,并且在填充路由值时没有类型检查。

有没有一种很好的方法来传输操作而不在查询字符串上暴露模型详细信息?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    如果在调用View 时没有指定视图名称,ASP.NET MVC 会尝试根据原始操作名称查找视图。

    因此,在您的情况下,尽管您已执行 Action2 并且想要显示 Action2.cshtml,但 MVC 将尝试将 Action1.cshtml 与您的 Action2Model 一起使用,这会引发此异常。

    您可以通过在操作中明确写出视图名称来解决此问题:

    public ActionResult Action1(Action1Model model)
    {
       //....
       if (...)
          return Action2(new Action2Model() { .... } );  //**
       else
          return View("Action1", model);
    }
    
    public ActionResult Action2(Action2Model model)
    {
         //...
         return View("Action2", model);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多