[英]How to load view from one controller using a different one?
Really simple question: I want to be able to redirect from one page to another in Razor MVC. 真正简单的问题:我希望能够在Razor MVC中从一页重定向到另一页。
The user clicks a link on the first page, which calls a method on the first controller. 用户单击第一页上的链接,该链接在第一控制器上调用方法。 This method uses data from its own model, as well as methods from the second controller, to construct a model for the second controller.
此方法使用其自身模型中的数据以及第二个控制器中的方法来构造第二个控制器的模型。
I now wish to display that second view using the newly constructed model. 现在,我希望使用新构建的模型来显示第二个视图。 However, there doesn't seem to be a way to use View() to do this (unless I'm blind).
但是,似乎没有办法使用View()来做到这一点(除非我是盲目的)。 The two controllers are in different folders, so it can't automatically find the page to load.
这两个控制器位于不同的文件夹中,因此它无法自动找到要加载的页面。
Any ideas? 有任何想法吗?
您可以使用类似
return View("../FolderName/ViewName", model);
It sounds like this has answered this question here: How to simulate Server.Transfer in ASP.NET MVC? 听起来这已经在这里回答了这个问题: 如何在ASP.NET MVC中模拟Server.Transfer?
In summary you should look at: 总之,您应该查看:
return RedirectToRoute(new { controller = "home"});
or look at some other redirection options: 或查看其他一些重定向选项:
Ideally you cannot return a view from Different Controller and Different Action. 理想情况下,您不能从“不同的控制器”和“不同的动作”返回视图。 But you can return a view from same controller and different action.
但是您可以从相同的控制器和不同的操作返回视图。
To Answer your question, We can always redirect to Different controller and Different Actions. 为了回答您的问题,我们始终可以重定向到不同的控制器和不同的动作。 In this scenario it will be a 302 GET request .So if you cannot pass models across Controllers.
在这种情况下,它将是302 GET请求 。因此,如果您无法在Controller之间传递模型。
(Though you can pass as route values,which will be appended in querystring.(This is not at all advised)) (尽管您可以传递路由值,但将其附加在查询字符串中。(不建议这样做))
Best approach will be either , 最好的方法是
1) Keep both the actions in same controller. 1)将两个动作保存在同一控制器中。
or 要么
2) Create the model with in the Action of 2nd Controller. 2)在第二控制器的动作中创建模型。
If the page should redirect to the correct URL for the second controller, I would: 如果页面应重定向到第二个控制器的正确URL,我将:
If you don't want a redirect, you might consider turning the actions from the first controller into an ActionFilter. 如果您不希望重定向,则可以考虑将操作从第一个控制器转换为ActionFilter。 That filter can be applied to both controller actions (first and second).
该过滤器可以应用于两个控制器动作(第一和第二)。 Your initial view would post to the second controller directly and the ActionFilter would help create that part of your model.
您的初始视图将直接发布到第二个控制器,而ActionFilter将帮助创建模型的该部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.