简体   繁体   English

无法从其他控制器加载模型数据的局部视图

[英]Trouble loading a partial view from a different controller with model data

Quite new to MVC so please bear with me. 对MVC来说还很陌生,所以请忍受我。 I'm trying to load a partial view in a modal from a different controller and everytime I try to view it I get just an empty modal. 我试图从其他控制器以模态加载局部视图,每次尝试查看它时,我只会得到一个空模态。 I believe it is because I haven't been able to instantiate my model in the view. 我相信这是因为我无法在视图中实例化我的模型。

Eg I have a Controller 'Home' with a method 'Details' that returns a partialview from a different View folder. 例如,我有一个带有“详细信息”方法的控制器“主页”,该方法从另一个“视图”文件夹返回一个局部视图。 The native model to the controller is 'model', whereas the model belonging to my other controller is 'model2'. 控制器的本机模型是“模型”,而属于我的另一个控制器的模型是“模型2”。

public ActionResult Details() {
    model2.User = user;        //this is a global variable
    model2.GetDetails();

    return PartialView("~/Views/...Details", model2);
}

I'm sure the reason is because i'm missing the model data in the view. 我确定原因是因为我在视图中缺少模型数据。 I tried adding another @model... to the view but clearly this doesn't work. 我尝试向视图添加另一个@model ...,但是显然这不起作用。

Is there a way of doing what I am trying to accomplish? 有什么办法可以做我想完成的事情? It can even be a relatively dirty solution as this is a stopgap solution for the time being. 它甚至可能是一个相对较脏的解决方案,因为这暂时是权宜之计。

Reading back over this post it reads a little convoluted so if any clarification is needed please let me know. 仔细阅读这篇文章后,会感到有些困惑,因此,如果需要任何说明,请告诉我。

Thanks 谢谢

I faced this problem once before and i think it's a lot of work to reproduce it to provide an exact solution, but I can offer my 2 cents. 我以前曾经遇到过这个问题,我认为复制它以提供精确的解决方案需要很多工作,但是我可以提供2美分。 The thing with browser Modals is that you need to provide a url when you are opening it. 使用浏览器Modals的事情是,在打开它时需要提供一个URL。 The URL will have to be the Controller/Action url and this is the tricky part which causes the problem. 该URL必须是Controller / Action URL,这是导致问题的棘手部分。 If you can figure that out, you should be able to solve the problem. 如果您能弄清楚,您应该可以解决问题。 If you can't, you can do one of the following: 1. Set the HTML content of Modal dialog from your main window's JS code after the Modal is opened. 如果不能,则可以执行以下操作之一:1.打开Modal后,从主窗口的JS代码中设置Modal对话框的HTML内容。 2. Use one of the 3rd party HTML/CSS modal implementation, and set the HTML content from the JS code. 2.使用第三方HTML / CSS模态实现之一,然后从JS代码中设置HTML内容。 In this case there is no browser modal and everything is on the same page. 在这种情况下,没有浏览器模式,所有内容都在同一页面上。

To verify if the view is returning correctly from XHR, put the actionRoute URL in the browser address bar and you will see the content getting returned. 要验证视图是否从XHR中正确返回,请将actionRoute URL放在浏览器地址栏中,您将看到返回的内容。 It will help with troubleshooting. 这将有助于进行故障排除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM