4

I was trying to render a dynamic view into string.I got the idea from here and it is working well locally but on hosting I am getting the following error.My attempt is to convert the string to bytes for sending email

Value cannot be null. Parameter name: view

Controller

public ActionResult Index(int RegId)
    {
        try
        {
            var _mdlReceiptPdf = new ReceiptPdfVM
            {
                ...
                ...
            };

            string result = RazorViewToString.RenderRazorViewToString(this, Server.MapPath("~/Views/Shared/_Receipts.cshtml"), _mdlReceiptPdf);
            StringReader _sr = new StringReader(result);            

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(ex.Message, JsonRequestBehavior.AllowGet);
        }          
    }

Util.cs

public static class RazorViewToString
    {

        public static string RenderRazorViewToString(this Controller controller, string viewName, object model)
        {

            controller.ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }

    }
Community
  • 1
  • 1
ksg
  • 3,927
  • 7
  • 51
  • 97
  • I assume you are calling this with ajax? If so are you setting the expected data type to be returned as json? For security reasons, ASP.NET AJAX will not provide the json serialised response unless you specify this. In debug this rule will not apply. Try adding dataType: "json", to your ajax call – Emma Middlebrook Jan 28 '16 at 10:26

2 Answers2

4

I had this problem. In my case, it turned out that the partial view wasn't being uploaded to the hosted website because in the File Properties for the partial view, the BuildAction was set to None instead of Content

Paul Bullivant
  • 668
  • 7
  • 13
2

Yeah looks like this error is saying view can't be found. In my case I had a typo for the view name in the controller. _QuickView.cshtml instead of QuickView.cshtml

Web Devvy
  • 55
  • 9