如何提供模型查看?

时间:2013-02-22 16:03:16

标签: c# asp.net asp.net-mvc

这是我的代码:

        [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文件发送。 这是一个强类型视图。

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

1 个答案:

答案 0 :(得分:4)

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

    [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");
    }