简体   繁体   English

调用View(Object model)时如何确定使用哪个View

[英]How do I determine which View is used when calling View(Object model)

First, some context: 首先,一些背景:

  • Language - C# 语言-C#
  • Platform - .Net Framework 4.5 平台-.Net Framework 4.5
  • Project type - ASP.Net MVC 4 项目类型-ASP.Net MVC 4

I am trying to determine which View in an MVC project is handling an explicit call to the following method. 我试图确定MVC项目中的哪个View正在处理对以下方法的显式调用。 The MSDN docs for the method are here: http://msdn.microsoft.com/EN-US/library/dd492930.aspx 该方法的MSDN文档在这里: http : //msdn.microsoft.com/EN-US/library/dd492930.aspx

protected internal ViewResult View(
    Object model
)

The original Author is using a View to generate a PDF file with a third-party library. 原始作者使用“视图”生成带有第三方库的PDF文件。 I need to modify the view to include additional information. 我需要修改视图以包括其他信息。

The problem: I'm having trouble finding which View to modify. 问题:我在查找要修改的视图时遇到麻烦。 There are hundreds of them, and (IMHO) they are poorly named and organized. 它们有数百个,而且(恕我直言)它们的名称和组织不善。 The basic process for generating a PDF looks like this. 生成PDF的基本过程如下所示。 I'm getting confused in between steps 3 and 4. 我在步骤3和4之间感到困惑。

  1. An Entity's ID is passed to an ActionResult 实体的ID传递给ActionResult
  2. The Entity is retrieved from the backing store 从后备存储中检索实体
  3. The model is passed to the Controller.View method mentioned above: 该模型将传递到上面提到的Controller.View方法:
    var viewModel = View(model) ; var viewModel = View(model) ;
    var xmlText = RenderActionResultToString( viewModel ); var xmlText = RenderActionResultToString( viewModel );
  4. The resulting ViewResult is used with an instance of ControllerContext to generate HTML as if being requested by a browser. 生成的ViewResult与ControllerContext实例一起使用,以生成HTML,就像浏览器请求的一样。
  5. The resulting HTML is passed to the third-party tool and converted to a PDF. 生成的HTML传递给第三方工具,然后转换为PDF。

I understand everything else very clearly. 我对其他所有事情都非常清楚。 What I don't understand is how the call to View(model) determines which View file to use when returning the ViewResult. 我不明白的是,对View(model)的调用如何确定返回ViewResult时要使用哪个View文件。 Any help greatly appreciated! 任何帮助,不胜感激!

I'm including the code below, in case it helps anybody determine the answer. 我包含以下代码,以防任何人确定答案。

The ActionResult: 动作结果:

public ActionResult ProposalPDF(String id, String location, bool hidePrices = false)
{
    var proposal = _adc.Proposal.GetByKey(int.Parse(id));

    var opportunity = _adc.Opportunity.GetByKey(proposal.FkOpportunityId.Value);
    ViewData["AccountId"] = opportunity.FkAccountId;
    ViewData["AccountType"] = opportunity.FkAccount.FkAccountTypeId;

    ViewData["Location"] = location;
    ViewData["HidePrices"] = hidePrices;
    return ViewPdf(proposal);
}

The ViewPDF method: ViewPDF方法:

protected ActionResult ViewPdf(object model)
{
    // Create the iTextSharp document.
    var document = new Document(PageSize.LETTER);

    // Set the document to write to memory.
    var memoryStream = new MemoryStream();
    var pdfWriter = PdfWriter.GetInstance(document, memoryStream);
    pdfWriter.CloseStream = false;
    document.Open();

    // Render the view xml to a string, then parse that string into an XML dom.
    var viewModel = View(model);
    var xmlText = RenderActionResultToString(viewModel);

    var htmlPipelineContext = new HtmlPipelineContext();
    htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

    //CSS stuff
    var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
    var cssResolverPipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, pdfWriter)));

    var xmlWorker = new XMLWorker(cssResolverPipeline, true);
    var xmlParser = new XMLParser(xmlWorker);

    xmlParser.Parse(new StringReader(xmlText));

    // Close and get the resulted binary data.
    document.Close();

    var buffer = new byte[memoryStream.Position];
    memoryStream.Position = 0;
    memoryStream.Read(buffer, 0, buffer.Length);

    // Send the binary data to the browser.
    return new BinaryContentResult(buffer, "application/pdf");
}

The RenderActionResultToString helper method: RenderActionResultToString帮助器方法:

protected string RenderActionResultToString(ActionResult result)
{
    // Create memory writer.
    var sb = new StringBuilder();
    var memWriter = new StringWriter(sb);

    // Create fake http context to render the view.
    var fakeResponse = new HttpResponse(memWriter);
    var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request, fakeResponse);
    var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), this.ControllerContext.RouteData, this.ControllerContext.Controller);
    var oldContext = System.Web.HttpContext.Current;
    System.Web.HttpContext.Current = fakeContext;

    // Render the view.
    result.ExecuteResult(fakeControllerContext);

    // Restore data.
    System.Web.HttpContext.Current = oldContext;

    // Flush memory and return output.
    memWriter.Flush();
    return sb.ToString();
}

The logic to determine which view template will be used is in the ViewResult that is returned from the call 确定使用哪个视图模板的逻辑在调用返回的ViewResult

var viewModel = View(model);

And how the view is selected is determined by the configured ViewEngine(s), but it will use the current Area , Controller and Action route values to determine what view should be served. 以及如何选择视图由配置的ViewEngine决定,但是它将使用当前AreaControllerAction路线值来确定应提供的视图。

What the route values are for the ProposalPDF action will depend on how your routing is configured, but assuming the defaults, the action route value will be ProposalPDF , the controller route value will be the name of the controller class in which this action resides (minus the Controller suffix) and the area will be the area folder in which the controller lives, with a value of empty string if in the default controller folder. ProposalPDF操作的路由值是什么,将取决于路由的配置方式,但是如果采用默认设置,则操作路由值将为ProposalPDF ,控制器路由值将是该操作所在的控制器类的名称(减号)。 (控制器后缀),区域将是控制器所在的区域文件夹,如果在默认控制器文件夹中,则为空字符串。 Then using these route values, a view will be looked up in the Views folder using the following convention 然后使用这些路由值,将使用以下约定在“视图”文件夹中查找视图

~/Views/{Area}/{Controller}/{View}.cshtml

There is always Glimpse that can help with providing runtime Diagnostics too, such as which View file was used to serve up the returned page, although I'm not sure how this would look when a ViewResult is executed internally to provide the contents of a file. 总有Glimpse可以帮助提供运行时诊断,例如使用哪个View文件提供返回的页面,尽管我不确定内部执行ViewResult以提供文件内容时的外观如何。

I'm not exactly sure what you're asking, but, when you call View(model) the view that is chosen is based upon conventions. 我不确定您要问的什么,但是,当您调用View(model) ,所选择的视图是基于约定的。

Here is an example: 这是一个例子:

public class HerbController : Controller {
    public ActionResult Cilantro(SomeType model) {
        return View(model)
    }
}

That will look for a view file called Cilantro.cshtml in a folder called Herb (Views/Herb/Cilantro.cshtml). 这将在名为Herb的文件夹(Views / Herb / Cilantro.cshtml)中查找名为Cilantro.cshtml的视图文件。 The framework will also look in the Shared directory as well in case it is a view that is meant to be shared across multiple results. 该框架还将在Shared目录中查找,以防该视图可在多个结果之间共享。

However, you may also want to look at the Global.asax file to see if there are any custom view paths being setup for the view engine. 但是,您可能还需要查看Global.asax文件,以查看是否为视图引擎设置了任何自定义视图路径。 The example I gave above is based upon the default conventions of ASP.NET MVC. 我上面给出的示例基于ASP.NET MVC的默认约定。 You can override them to meet your needs better if needed. 如果需要,您可以覆盖它们以更好地满足您的需求。

The convention for views is that they are in a folder named after the controller (without "Controller") and the .cshtml file inside that folder is named after the calling action. 视图的约定是,它们位于以控制器命名的文件夹中(不带“ Controller”),并且该文件夹中的.cshtml文件是根据调用操作命名的。 In your case, that should be: 在您的情况下,应为:

~/Views/[Controller]/ProposalPdf.cshtml

暂无
暂无

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

相关问题 确定在不使用返回视图(模型)时返回哪个ASP.NET MVC视图但返回View(“viewName”,model) - Determine which ASP.NET MVC View to return when not using return View(model) but return View(“viewName”, model) 如何从模型类型为IEnumerable的视图传递一个ID到部分视图 - How do I pass one ID from a view which has a Model Type of IEnumerable to aPartial View 在指定对象的变量时,如何将对象从模型传递到视图? - How do you pass an object from the model to the view while specifying which variable of the object? 当用于在details.cshtml页面上查看时,我用什么代码来查看模型中的项目列表? - what code do I use to view a list of items from the model when used to view on the details.cshtml page? 当父视图具有相同模型时,如何将局部视图中的 HTML 表单数据序列化? - How do I get HTML form data in Partial View to be serialized when parent view has same model? 如何获取视图中视图模型的属性? - How do I get to the properties of the view model in the view? 如何在运行时设置视图/视图模型数据模板? - How do I set view/view model data template at runtime? 如何将可能不是模型的对象从控制器返回到View - How to return an object from controller to View which may not be model 如何切换依赖于哪个视图 model object 的内容模板? - How to switch contenttemplate dependent which view model object? 如何确定使用哪个适配器? - How do you determine which adapter is used?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM