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

发布于 2024-12-17 04:35:14 字数 412 浏览 0 评论 0原文

从控制器返回不同的视图确实很容易:

return View("../Home/Info");

但是,我需要信息视图中的模型。我在 Info() 操作结果方法中发生了很多事情。我可以复制它并得到类似这样的内容:

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

但这是不合理的。

当然我可以直接重定向:

return RedirecToAction("Info");

但是这样URL就会改变。我不想更改网址。这非常重要。

It's really easy to return a different View from the Controller:

return View("../Home/Info");

However, I need a model in the Info view. I have a lot of stuff going on in the Info() action result method. I can just copy it and have something like this:

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

But that is not reasonable.

Of course I can just redirect:

return RedirecToAction("Info");

But this way the URL will change. I don't want to change the URL. That's very important.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

脸赞 2024-12-24 04:35:14

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

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{...});
}

You can call right to another action from within an action, like this:

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{...});
}
痴者 2024-12-24 04:35:14

It looks like you want to invoke an action from a different controller. I'd suggest that you might want to simply render a view that renders that action using Html.Action() instead of trying to tie the two together in the controller. If that's unreasonable then you might want to create a base controller that both controllers can derive from and put the shared code to generate the model in base controller. Reuse the view as needed.

  public ActionResult Foo()
  {
      return View();
  }

Foo View

  @Html.Action( "info", "home" ) 
[旋木] 2024-12-24 04:35:14

为什么不直接调用操作的方法呢?

Why not just invoke the method of the action?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文