1

这是我的代码:

        [HttpGet]
        public FileContentResult GetCalenderView()
        {
            StringWriter sw = new StringWriter();
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, "GetCalenderView");
            ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            var stringResult = sw.GetStringBuilder().ToString();

            byte[] byteArray = Encoding.ASCII.GetBytes(stringResult);

            return File(byteArray, "application/octet-stream", "Month.xls");
        }

我在网上找到了这个。它的作用是给我字符串格式的视图,然后我将其作为 excel 文件发送。这是一个强类型视图。

我的问题是,我如何为这个视图提供模型?

4

1 回答 1

6

设置Model您传入的 ViewData 的属性。

    [HttpGet]
    public FileContentResult GetCalenderView()
    {
        var viewData = ViewData; // Ideally copy this or make a fake of it
        viewData.Model = new object(); // Make this the model you want to pass in

        StringWriter sw = new StringWriter();
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, "GetCalenderView");
        // Note that we're passing in viewData instead of ViewData
        ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, viewData, this.TempData, sw);
        viewResult.View.Render(viewContext, sw);

        var stringResult = sw.GetStringBuilder().ToString();

        byte[] byteArray = Encoding.ASCII.GetBytes(stringResult);

        return File(byteArray, "application/octet-stream", "Month.xls");
    }
于 2013-02-22T16:08:01.707 回答