Incorporating an MVC View into a sophisticated JsonResult response

When I request Views from the MVC backend, I need more than just the content:

public class CustomJsonViewResult
{
    public string Subject { get; set; }

    public ActionResult View { get; set; }
}

As time goes on, this class will become more complex.

To implement this in a Controller method, you can do:

public JsonResult Person()
{
    return Json(new CustomJsonViewResult
    {
        View = View(),
        Subject = "Update an existing person"
    }, JsonRequestBehavior.AllowGet);
}

The subject value should be determined dynamically in the future instead of being static.

In my AngularJS directive, I have a link like this:

link: function (scope, element, attrs) {
    screensService.GetPartialView(attrs.view).then(function (viewData) {

        var linkFunc = $compile(viewData.View);
        var content = linkFunc(scope);
        element.append(content);
    });
}

This code works when returning the ActionResult directly, but currently I am encountering this error:

typeError: Cannot read property 'ownerDocument' of undefined
    at Function.Sizzle.contains (jquery-2.1.4.js:1430)
    at Function.jQuery.extend.buildFragment (jquery-2.1.4.js:5147)
    at jQuery.fn.extend.domManip (jquery-2.1.4.js:5387)
    at jQuery.fn.extend.append (jquery-2.1.4.js:5218)
    at PartialViewLoaderDirective.js:27
    at processQueue (angular.js:14569)
    at angular.js:14585
    at Scope.$get.Scope.$eval (angular.js:15848)
    at Scope.$get.Scope.$digest (angular.js:15659)
    at Scope.$get.Scope.$apply (angular.js:15953)

When I log viewData to console, it shows:

Object {Subject: "Update an existing person", View: Object}
    Subject: "Update an existing person"
    View: Object
    MasterName: ""
    Model: null
    TempData: Array[0]
    View: null
    ViewBag: Object
    ViewData: Array[0]
    ViewEngineCollection: Array[2]
    ViewName: ""
    jQuery21400306884015444666152: 19
    __proto__: Object
    __proto__: Object

To Summarize:

Any thoughts on why I'm getting this Cannot read property 'ownerDocument' of undefined error? Everything seems to be as expected.

Answer №1

I managed to successfully implement the solution using the URL method:

public ActionResult Person()
{
    return View();
}

public JsonResult PersonAsJson()
{
    return Json(new CustomJsonViewResult
    {
        Url = Url.Action("Person"),
        Subject = "Update an existing person"
    }, JsonRequestBehavior.AllowGet);
}

On the client side, the following code was used:

screensService.GetPartialView(attrs.view).then(function (viewData) {
    $.post(viewData.Url, function (view) {
        var linkFunc = $compile(view);
        var content = linkFunc(scope);
        element.append(content);
    });
});

Unfortunately, RenderRazorViewToString did not work as expected because ViewData.Model couldn't be found by the compiler or Resharper.

Similarly, RenderView didn't work due to the inability to provide a ViewResult into a ViewContext.

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for me to interact with different elements upon hovering?

html, <div id="first"> <a>Click here</a> </div> <div id=second"> second div content </div> css, #first a:hover{ color:blue; /*change color on hover */ #second{ background:blue; } } In ...

Managing both TCP/IP raw requests and HTTP requests on a single server requires careful configuration and resource allocation

I have developed a GPS tracking system and implemented a server using Node.js. Below is the code snippet for reference. const net = require('net'); const lora_packet = require('lora-packet'); const dataParser = require('./dataPars ...

Aligning the ant design carousel in the center of the page

I adjusted the size of an Ant Design carousel and now I want to position the image in the center of my screen. This is how the current image looks: https://i.sstatic.net/TmfDb.png Here is what I have attempted: const contentStyle = { heigh ...

What could be causing the error I'm encountering while attempting to utilize Array.includes as the function for Array.filter in my JavaScript code?

During a recent javascript project, I attempted something like the following code snippet. To my surprise, it did not work and instead produced an error message. const test = [1, 2, 3, 4]; const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(test.includes) ...

Exploring the power of SSE using AngularJS and Java within the Play framework

I am new to working with Server-Sent Events (SSE), so I decided to create a website that utilizes SSE. On the client side, I am using AngularJS and making server requests with Restangular. The server side is written in Java. I have already implemented POST ...

Move your cursor over the image to activate the effect, then hover over it again to make the effect disappear

Looking to enhance my images with hover effects. Currently, all the images are in grayscale and I'd like to change that so that when you hover over an image, it reverts to full color and remains that way until hovered over again. I've noticed so ...

What is causing the error message 'undefined is not a function' to appear in my code?

Struggling to send a file in response to a GET request with express.js. I created a basic FileManager class to manage file requests, yet encountering an error of 'undefined is not a function' when calling new FileManager() Here's my approac ...

What purpose does the HttpException serve in ASP.NET MVC?

I'm a bit puzzled by the HttpException Exception class in ASP.NET MVC 4. I know it allows you to throw custom error codes, but there's another constructor that takes a message as well: HttpException Constructor From what I understand, HTTP only ...

Issues arise when trying to access JSON data that has been added to an array using the JavaScript .push method

I am encountering an issue where I cannot retrieve values from an array after storing it in a variable outside of the getJSON function. The response in JSON format looks like this: [ { "Book_ID": "1", "Book_Name": "Computer Architectu ...

How to sequentially load multiple obj files in Three.js

Currently, I am utilizing the obj/mtl loader from three.js to import various obj files along with mtl files. The challenge I am facing now is the need to load multiple objs one by one. Even though I have implemented THREE.DefaultLoadingManager.onProgress t ...

"PHP, AJAX, and JavaScript work together to run a loop that processes only the final element

Hello everyone, I need assistance in saving data from a loop. Here is the code snippet that I am working with: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> ...

Make sure to verify the existence of the file before retrieving its contents

Having some trouble with my ajax code that is meant to retrieve the contents of a text file on the server and display it in a textarea. When the file does not exist, a 404 error appears in the console. I attempted using PHP instead, but encountered an iss ...

Converting nested JSON structures into a PySpark DataFrame

Looking for a simple way to convert the provided JSON sample into a PySpark dataframe? Input : { "user": { "1": { "name": "Joe", "age": 28 }, "2" :{ "name": "Chr ...

InvalidType error occurred during JSON array conversion of the dictionary

Can someone help me with converting a Python dictionary containing string keys and values into a JSON string? This is the code I have so far: import json def create_simple_meeting(subject, startDate, endDate, location, body): info = dict() if(su ...

Constructing Instances from JSON Data

Is there a reliable method to generate an NSArray or NSDictionary from a JSON string received from a web service? I am currently utilizing the json framework for this purpose. The expected format of the response string is as follows: {count:2, data ...

VueJS - Validating Props with Objects

What is the best way to validate Object type props in VueJS to guarantee that certain fields are defined within the object? For instance, I need to make sure that the user prop includes 'name', 'birthDate', and other specific fields. ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

Transferring Data from Cookie to Drift's Custom Attribute

Seeking assistance: Currently, I am attempting to transfer data from a Cookie in GTM to a custom attribute inside Drift. I have referred to this documentation, but unfortunately, the implementation seems to be failing: Below is the code snippet that I h ...

PNG metadata was not saved or read during the write/read process

My functions are designed to write and read meta-data into/from PNG files. The code I am using is an adaptation of an MSDN example for C#, but despite no errors, nothing is being written to the file (I even checked with a tool called tweakpng). I have co ...

Burst Specification bypassing initial item in array

Here is the JSON Input : [ { "e": "id1", "c": [ { "title": "title1", "enable": false } ] }, { "e": "id2", "c": [ ...