ASP.NET MVC:如何使用模型呈现不同的操作(而不是视图)?

Ale*_*lex 4 asp.net-mvc action controller

从Controller返回不同的视图非常容易:

return View("../Home/Info");
Run Code Online (Sandbox Code Playgroud)

但是,我需要在Info视图中使用一个模型.我在Info()动作结果方法中有很多东西.我可以复制它,并有这样的事情:

var infoModel = new InfoModel {
    // ... a lot of copied code here
}
return View("../Home/Info", infoModel);
Run Code Online (Sandbox Code Playgroud)

但那是不合理的.

当然我可以重定向:

return RedirecToAction("Info");
Run Code Online (Sandbox Code Playgroud)

但这样URL就会改变.我不想更改URL.这非常重要.

And*_*ber 9

您可以在操作中调用另一个操作,如下所示:

public ActionResult MyAction(){
   if(somethingOrAnother){
      return MyOtherAction();
   }
   return View();
}

//"WhichEverViewYouNeed" is required here since you are returning this view from another action
//if you don't specify it, it would return the original action's view
public ActionResult MyOtherAction(){
    return View("WhichEverViewYouNeed", new InfoModel{...});
}
Run Code Online (Sandbox Code Playgroud)

  • 除非您明确指定要显示的视图,否则视图将对应于最初调用的操作. (4认同)
  • 是的,但在您的示例中,即使调用了*MyOtherAction*,它仍会查找*MyAction*视图.你需要做一个`return View("MyOtherAction",新的InfoModel {...});`如果你一直想要渲染随之而来的视图. (3认同)

tva*_*son 8

看起来您想要从不同的控制器调用操作.我建议您可能只想渲染一个视图,该视图使用Html.Action()呈现该操作,而不是尝试将两者绑定在控制器中.如果这是不合理的,那么您可能想要创建一个基本控制器,两个控制器都可以从中派生并放置共享代码以在基本控制器中生成模型.根据需要重用视图.

  public ActionResult Foo()
  {
      return View();
  }
Run Code Online (Sandbox Code Playgroud)

Foo View

  @Html.Action( "info", "home" ) 
Run Code Online (Sandbox Code Playgroud)