1

My searching failed to find what I thought would be a well travelled subject. My options outlined at the bottom reflect some things I found.

I need to render a view from the server side as a ViewModel or via a JSON object. The JSON object would come from server.

On client side I use ajax and sometimes I determine insertion based on other id/attributes on the page as to whether I append/prepend/replace or ignore-placing to the target element.

What options do I have to use the same view for ViewModels or JSON objects?

I had considered, on compile, render a File.Js version of the view. Include that as a resource on the page and perform replaces on the var ViewHtmlTemplate = "<div>@Model.Message</div>. I would have to be very disciplined in moving all formatting/if-statement logic to the viewmodel which would also be JSON serialized.

Or, that the view has a script tag to bind the ViewModel serilized to a js var and then run a function on document ready.

The 3rd option is instead of returning a JSON object, to return an array of serverside already html-rendered views.

1
  • you can use other methods like JQuery.load. otherwise use a JQuery Ajax call Commented Apr 8, 2013 at 23:38

2 Answers 2

1

What I do is inside of my view model I will have a field which is a string which is a serialized json structure.

public class SomeVM
{
 /* other properties */
 public string jsonString { get; set; }
}

In the controller I will serialize some data into the jsonString. Then in the view, I will assign the string to a variable

@model SomeVM
<script>
 var jsonVM = @( Html.Raw(Model.jsonString) );
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

I am using the solution which returns the Html in the json object. If there are any problems with doing that please let me know. Here is how I went about it.

Controller extension to render partial a view (included but not used in this solution is RenderViewToString). This can be found in various forms across different answers which did not seem to match my customized version which I do not take credit for.

namespace System.Web.Mvc
{
    using System.IO;

    public static class MvcControllerExtension
    {
        public static string RenderPartialViewToString(this Controller controller, string viewName = null, object model = null)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }

            controller.ViewData.Model = model;

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

        public static string RenderViewToString(this Controller controller, string viewName = null, object model = null, string masterName = null)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }

            controller.ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName);
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }
    }
}

In the controller action returning JsonResult

public JsonResult _DisplayByFoo(int catId)
{
    var myRealModel = new MyRealModel(catId);
    // .... omitted the construction of MyRealModel
    var jsonModel = new JsonModel(myRealModel);
    jsonModel.Html = this.RenderPartialViewToString("_Display", myRealModel);
    return Json(jsonModel);
}

I also include other properties on the json object which help me determine my insertion mode.

In Js; after my AjaxCall to the Json action. Run OnSuccess method, which, apart from other logic, does the following.

$("#" + targetId).append(MyJson.Html);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.