ASP.NET MVC:如何使用模型呈现不同的操作(而不是视图)?
从控制器返回不同的视图确实很容易:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以从一个操作中直接调用另一个操作,如下所示:
You can call right to another action from within an action, like this:
看起来您想从不同的控制器调用操作。我建议您可能只想简单地呈现一个使用 Html.Action()< 呈现该操作的视图/a> 而不是尝试在控制器中将两者结合在一起。如果这是不合理的,那么您可能需要创建一个两个控制器都可以派生的基本控制器,并将共享代码放在基本控制器中生成模型。根据需要重用视图。
富视图
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.
Foo View
为什么不直接调用操作的方法呢?
Why not just invoke the method of the action?