0

I am trying to take a partial view and return a html string representation so that I can pass that back on an ajax request and set a div tag to .html().

At the top of the partial, I add html attributes of hidden values @Html.Hidden() and @Html.HiddenFor() to store those values in the html.

The error is at the bottom.

I've tried to figure out if any values of my model are NULL

Code to convert the partial to an HTML string

        public static string RenderViewToString(ControllerContext context, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = context.RouteData.GetRequiredString("action");
            }

            var viewData = new ViewDataDictionary(model);

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
                var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

Here is my partial view

@using WebPortal.MVC.Utilities.Controls;
@model WebPortal.MVC.Models.Controls.DxGridView.DxGridViewControlModel


@Html.Hidden("dxGridName", Model.Name)
@Html.Hidden("dxGridId", Model.Id)
@Html.Hidden("dxPageSize", Model.Paging.PageSize)
@Html.HiddenFor(x => x.HasFilterRowFunctionality)
@Html.HiddenFor(x => x.HasRefreshFunctionality)
@Html.HiddenFor(x => x.HasHeaderFilterFunctionality)
@Html.HiddenFor(x => x.HasSavedLayoutFunctionality)
@Html.HiddenFor(x => x.HasExportToSpreadsheetFunctionality)
@Html.HiddenFor(x => x.HasExportFunctionality)
@Html.HiddenFor(x => x.OnLoadGridLayoutId)
@Html.HiddenFor(x => x.ConvertDateTimeToLocal)
@Html.HiddenFor(x => x.HeightAdjust)
@Html.HiddenFor(x => x.KeyFieldName)
@Html.HiddenFor(x => x.CurrentUserId)

<div class="dxgridControlContainer">
    @(Html.DevExtreme()
                .DataGrid<WebPortal.MVC.Models.Controls.DxGridView.DxGridViewControlModel>()
                .ID(Model.Id)
                .Width("100%")
                .Height("700px"))
</div>

I am expecting this partial to be turned into a HTML string without the below error.

If you REMOVE ALL of the @Html.Hidden() and @Html.HiddenFor() in the partial view it works perfect.

I need those values to be on the page so I can use them in my java-script.

Or is there a better way to place the values on the page so that I can use them? Appears doing a Hidden or HiddenFor is causing some error handling to fail.

Any help would be appreciated.

Error:

System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.WebPages.Scope.AspNetRequestScopeStorageProvider.get_RequestScopeInternal() at System.Web.WebPages.Scope.AspNetRequestScopeStorageProvider.get_CurrentScope() at System.Web.Mvc.PreApplicationStartCode.<>c.b__1_0() at System.Web.Mvc.ViewContext.get_Scope() at System.Web.Mvc.ViewContext.get_UnobtrusiveJavaScriptEnabled() at System.Web.Mvc.HtmlHelper.GetUnobtrusiveValidationAttributes(String name, ModelMetadata metadata) at System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, String format, IDictionary2 htmlAttributes) at System.Web.Mvc.Html.InputExtensions.HiddenHelper(HtmlHelper htmlHelper, ModelMetadata metadata, Object value, Boolean useViewData, String expression, IDictionary2 htmlAttributes) at System.Web.Mvc.Html.InputExtensions.HiddenFor[TModel,TProperty](HtmlHelper1 htmlHelper, Expression1 expression, IDictionary2 htmlAttributes) at System.Web.Mvc.Html.InputExtensions.HiddenFor[TModel,TProperty](HtmlHelper1 htmlHelper, Expression1 expression) at ASP._Page_Views_Shared_Controls_GridView__DxGridViewControlPartial_cshtml.Execute() in MyPartialridView\_DxGridViewControlPartial.cshtml:line 8 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) at WebPortal.MVC.Utilities.ViewHelper.RenderViewToString(ControllerContext context, String viewName, Object model) in ViewHelper.cs:line 31 at WebPortal.MVC.Areas.DataVisualization.Controllers.DataVisualizationController.<RenderPivotGridDrillDownPartialView>d__2.MoveNext() in Controller.cs:line 71 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_6.b__4() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.b__1(IAsyncResult asyncResult)

tvb108108
  • 398
  • 3
  • 19

1 Answers1

0

Try calling viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View); after viewResult.View.Render(viewContext, sw);. Also, can you debug and see what property throws null error?

Y Stroli
  • 339
  • 3
  • 8
  • @Y Stroli, I'll try that. Well not sure how to debug it because if I remove ALL of the Hidden() additions with the Html helper, then it works, if I just leave one in, it fails – tvb108108 Sep 02 '19 at 23:30
  • @Y Stroli, it fails on that line: viewResult.View.Render(viewContext, sw); so placing that new line after it will do no help. – tvb108108 Sep 02 '19 at 23:32
  • I reread your question and I'm not sure why you can't just call a ActionResult method that returns a partial view from ajax and use that to populate your div. as for the error check if viewContext.Model is set to an instance of DxGridViewControlModel – Y Stroli Sep 03 '19 at 00:06
  • @Y Stroil - can you give me an example of calling the partial view from ajax and populate the div tag there? Like how would I do that in javscript? Maybe I'm doing it wrong in this case? I'll check that here soon and respond back on if the viewcontext.Model is set to: DxGridViewControlModel – tvb108108 Sep 03 '19 at 00:07
  • https://stackoverflow.com/questions/3490059/return-a-partialview-from-ajax-post --> this might be what I need. The 1st answer might have done it. Still testing. Let me get all the code working and I'll respond back to you! – tvb108108 Sep 03 '19 at 00:19
  • @Y Stroli - I think I got it fixed a totally different way per say. I did what you said with returning a Partial View and it works now. I had to add the div tag a different way which was messing me up for a bit. Thanks. – tvb108108 Sep 03 '19 at 03:18