Pass the ASP.NET MVC model onto the AngularJS scope

Here is the code snippet from my view with temporary JavaScript code for testing:

I am trying to assign the ASP.NET MVC model (@Model) to the AngularJS scope ($scope.person).

Any suggestions on how to accomplish this?

Thank you,

The View

@model MyApp.Person

<script>
var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = ?????
}]);
</script>

Update 1 : I attempted the following code in the JS file:

var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = @Html.Raw(window.person);
}]);

In the view file:

<script>
    @{
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    }
    window.person = serializer.Serialize(Model);
</script>

I encountered 2 errors:

ReferenceError: serializer is not defined (on windows)
window.person = serializer.Serialize(Model);

SyntaxError: illegal character (it's the @)
$scope.person = @Html.Raw(window.person);

Answer №1

<script>
    @{
        var converter = new System.Web.Script.Serialization.JavaScriptSerializer();
        var data = converter.Serialize(Model);
    }
    var myApp = angular.module('myApp', []);

    myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
        $scope.personData = @Html.Raw(data);
    }]);
</script>

Answer №2

Not certain if this will be compatible with Angular.

You have the option to utilize the Json.Encode Method which converts a data object into a string formatted in JavaScript Object Notation (JSON).

window.person = @Html.Raw(Json.Encode(Model)); //Saving data as a global variable.

In your Angular code, use:

$scope.person = window.person

Alternatively, it would be recommended to create a service for fetching person data.

Full Code Example

@model MyApp.Person

<script>
window.person = @Html.Raw(Json.Encode(Model)); //Saving data as a global variable.
var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.myPerson = window.person
}]);
</script>

Answer №3

I encountered a similar issue, but here’s a solution that should resolve it for you. In your perspective:

<script>
    myApp.value('individual', @Html.Raw(Model));
</script>

Then in your (angular) controller:

myApp.controller('individualController', ['$scope', '$http', 'individual' function ($scope, $http, individual) {
    console.log(individual);
}]);

By inserting your JSON data into the controller, you’ll be all set.

Answer №4

To start, set a value in a global JavaScript variable and then access it in a separate Angular file

 <script>
   var data =  '@Html.Raw(Model)';
</script>

Next, in your Angular script:

$scope.info = obj;

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

Providing static content within the generated code structure by Yeoman for the Angular Fullstack framework

I'm sticking to the code structure generated by Yeoman for an Angular fullstack application. The issue I'm facing is how to include a script called core.js in a file named app.html. <script src="core.js"></script> I can't fi ...

Having difficulty populating the token in the h-captcha-response innerHTML and g-recaptcha-response innerHTML

I am attempting to use 2captcha along with Selenium and Python to bypass an Hcaptcha. After receiving my 2captcha token, I attempt to input it into the textareas labeled 'h-captcha-response' and 'g-captcha-response'. However, this app ...

How can I turn off Angular Grid's virtualization feature, where Angular generates div elements for the grid based on height and width positions?

Currently, I am working with an Angular grid (ag-grid) that dynamically creates div elements in the DOM to display data as the user scrolls or views different sections. As part of my testing process using Selenium WebDriver, I need to retrieve this data fr ...

Tips for invoking Angular's native email validation function

Can Angular's internal email validation method be invoked from JavaScript instead of declaring it in the markup? Appreciate your help. UPDATE: I am interested in this because I want to ensure consistent email validation when using both the standard ...

Updating Angular JS views in real-time using database changes

I am currently in the process of building a social networking application using AngularJS. I have come across an issue regarding data binding. In my app, there is a timeline div where all the recent posts are displayed, along with a status updater at the t ...

My JavaScript/jQuery code isn't functioning properly - is there a restriction on the number of api calls that can be made on

Below is the code I have implemented from jquery ui tabs: <script> $(function(){ // Tabs $('#tabs1').tabs(); $('#tabs2').tabs(); $('#tabs3').tabs(); //hover states on the sta ...

How to show table cell value in Angular 4 using condition-based logic

I am a beginner in Angular development. Here is the HTML code I am working with: <tr *ngFor="let item of calendarTableSelected; let idx = index"> <span *ngIf="idx === 0"> <td style="width:15%;" *ngFor="let name of item.results" ...

Turning a lambda function into a function that is compatible with next.js API: A step-by-step guide

I am currently using an Instagram API to retrieve data from my personal profile, which is triggered by a lambda function on Netlify. Here is a snippet of the code: require('isomorphic-unfetch') const url = `https://www.instagram.com/graphql/quer ...

Difficulty with timing in React.js when rendering content from an Express.js API

I am facing a timing issue while working with React.js. My component checks the validity of the user's token and type. If the user is an admin, it should display certain content; otherwise, it should show "you don't have permission". However, I ...

Tips on invoking a function from an array in JavaScript when a button is clicked

Being new to JavaScript, I encountered a challenge where I have an array of functions: allFunctions = () => [ function1(), function2(), function3(), function4(), function5(), function6(), function7(), function8(), function9() ] My go ...

Angular can be used to compare two arrays and display the matching values in a table

Having two arrays of objects, I attempted to compare them and display the matching values in a table. While looping through both arrays and comparing them by Id, I was able to find three matches. However, when trying to display these values in a table, onl ...

Tips for organizing and concealing images within a Div for seamless transitions (no need for floats)

Currently, I am working on a grid layout for my website. My goal is to have 9 images load quickly, and then once the page has loaded, I want to fetch additional images, insert them into the image containers, and animate between them. While I understand how ...

Securing RESTful APIs with stringent security measures

Lately, I've been delving into using modern front end technologies such as React and Angular. This has led me to explore tools like JSON Server for simulating restful database interactions. I've noticed that most REST APIs require authentication ...

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

Adjust an OnDemandGrid utilizing dstore/Rest output through a POST request instead of a PUT request

I am facing a perplexing issue. I have an OnDemandGrid that is editable, and below it, I have a dstore/Rest collection connected to my backend (using PHP). While I can edit the data in the OnDemandGrid, I am unable to save it properly. When it reaches the ...

Missing parameter in the AJAX request

Looking for help with calling the AddCompare action method using an Ajax request in the View. The issue I'm facing is that the parameter sent to the AddCompare Action always has a value of zero, while the parameter value in the function AddToCompare ...

Using the Nodejs Array prototype filter method within a JSON object

Attempting to create a function that filters and returns specific strings within JSON data. Any advice is appreciated. Thank you! [ { line: '{"status":"waiting"}' } ] var body_W = []; body_W.push({line: JSON.stringif ...

How can we change a jQuery document click function to an inline onclick function?

Under certain circumstances, I have to refactor my click function into a standalone function and trigger it using inline onClick="myFunction();" This is my current code structure: $(document).on('click','.exBtn', function(){ var ex = ...

Retrieving text data in Controller by utilizing jQuery AJAX request

Text box and button for input <input type="text" class="form-control" name="ClaimNumber" placeholder="Enter a claim number" id="ClaimNumber" /> <button class="btn btnNormal" type="submit" id="btnSearch"> ...

Validation is not being enforced for the input field labeled as 'name' in the form

Can anyone assist me with a form validation issue I'm encountering while working on my project? The validation is functioning correctly for email and institution fields, but it seems to be ignoring the name field. Any suggestions or help would be grea ...