Send an object from AngularJS to an MVC controller and bind it to a corresponding class object

Trying to map an object from AngularJS to a custom C# class in an MVC controller, but encountering issues with the class object showing up as null. Here's the code snippet:

$scope.Get = function () {
    var EService = [{
        id: $scope.Id,
        servicename: $scope.ServiceName,
        servicetype: $scope.ServiceType,
        monthlyrental: $scope.MonthlyRental,
        serviceremarks: $scope.ServiceRemarks,
        servicestatus: $scope.status,
        activationdate: $scope.ActivationDate,
        deactivationdate: $scope.DeActivationDate
    }];

    $http.post('/TS/API/Insert', Service).then(function (res) {
        debugger;
    });

MVC Controller and Class:

[HttpPost] 
public string Insert(ServicesMaster Service)
{

    GIBCADBEntities gfientity = new GIBCADBEntities();

    var record = "Sent";
    return Json(record, JsonRequestBehavior.AllowGet); 
} 

public class ServicesMaster
{
    public string id { set; get; }
    public string servicename { set; get; }
    public string servicetype { set; get; }
    public int? monthlyrental { set; get; }
    public string serviceremarks { set; get; }
    public byte servicestatus { set; get; }
    public DateTime? activationdate { set; get; }
    public DateTime? deactivationdate { set; get; }
}

While the Javascript variable/object "EService" appears fine, when passing it only the ServicesMaster object is created with null values. Sending single strings or values works, but sending a complete object results in this behavior.

Answer №1

When passing an array from the front end and fetching an object from the server end, remember to remove the "[" and "]" braces when setting the value to EService. For example:

 $scope.Get = function () {
     var Service = {};
     Service = {
        id: $scope.Id,
        servicename: $scope.ServiceName,
        servicetype: $scope.ServiceType,
        monthlyrental: $scope.MonthlyRental,
        serviceremarks: $scope.ServiceRemarks,
        servicestatus: $scope.status,
        activationdate: $scope.ActivationDate,
        deactivationdate: $scope.DeActivationDate
     };

     $http.post('/TS/API/Insert', Service).then(function (res) {
        debugger;

     }); 
};

By following these steps, your code should now work properly. :)

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

Using JavaScript regex to match repeating subgroups

Can a regular expression capture all repeating and matching subgroups in one call? Consider a string like this: {{token id=foo1 class=foo2 attr1=foo3}} Where the number of attributes (e.g. id, class, attr1) are variable and can be any key=value pair. C ...

"Encountering a Syntax Error When Using request.post in Dojo Framework on Button Click

Here are three questions to consider: 1) What strategies can be utilized to streamline this code and reduce nesting and quote-related complications? 2) Are there any suggestions for addressing the parsing error mentioned below? I've already tested sep ...

Exploring the depths of Javascript scope with the Polymer starter-kit 2

When working on my-app.html ... <paper-icon-button icon="my-icons:menu" onclick="this.$._joesDrawerToggle()"></paper-icon-button> ... <script> Polymer({ is: 'my-app', ... _showPage404: function() { thi ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

Utilizing PHP variables to dynamically assign names to radio input tags, and then extracting their values using jQuery or JavaScript

I am facing an issue with my PHP file that generates radio buttons based on unique pets ids. The variable $idperro is constantly changing to distinguish the set of radio buttons. My goal is to insert the value inside the p tag. Here's the PHP code sn ...

Enhancing user engagement with PDF files using AngularJS to create an interactive and captivating page-turn

Anyone familiar with how to achieve a page turner effect for PDF files using Angular? I'm open to jQuery solutions as well. I've come across turn.js, which uses HTML, but I'm specifically looking for a way to implement this effect with PDF f ...

Vue alert: A duplicate key with the value of '10' has been identified. This could potentially lead to an issue with updates

I've been encountering a persistent error that I can't seem to resolve: [Vue warn]: Duplicate keys detected: '10'. This issue is causing an update error in my application. Despite trying the following steps, the error continues to appe ...

What is the best way to implement an ng-change function on multiple fields within the same page without causing a cyclic call loop?

In my page, I have three angular-moment-datepicker fields - a date picker field, a month picker field, and a year picker field respectively. Here is the code: <input class="form-control" placeholder="BY DAY" ng-model="date" moment-picker="gDate" start- ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

Error: The options object provided for CSS Loader is not valid and does not match the API schema. Please make sure to provide the correct options when

Summary My Nuxt.js project was created using the command yarn create nuxt-app in SPA mode. However, I encountered an error after installing Storybook where running yarn dev resulted in failure to start the demo page. ERROR Failed to compile with 1 errors ...

Can Sequelize be used to perform queries based on associations?

I have designed a data structure that includes an n:m relationship between "Rooms" and "Users." My current goal is to remove or delete a room. To accomplish this, I need to verify if the user initiating the deletion process is actually present in the room ...

Obtain the URL link from Unsplash where the picture is sourced

As I work on a website, I incorporate a link () to display a random photo. However, the photo refreshes periodically and upon loading the site, all that is visible is this default link: . Is there a method to extract the actual source like so: "". Althou ...

Exploring the dynamic creation of multiple gridviews

Is it possible to generate multiple gridviews? Here is my approach: GridView gv = new GridView(); Panel panel = new Panel(); for (int i = 0; i < DST.Tables.Count; i++) { gv.ID = DST.Tables[i].TableName; gv.DataSource = DST.Tables[ ...

Issue encountered while utilizing PHP sessions

I'm currently developing a basic login page that utilizes JS, JQuery, and PHP. login.php <!DOCTYPE html> <head> <title>AJAX Login Learning Activity</title> <link rel="stylesheet" type="text/css" href="login.css"> ...

Error encountered at / - undefined local variable or method `parameters' for main:Object (Executing Stripe Charge with Stripe.js)

Encountering an error with the code below while attempting to create a Stripe charge using Stripe.js. Below is my web.rb file: require 'json' require 'sinatra' require 'sinatra/reloader' require 'stripe' get &a ...

Exploring parameterized routing in Node.js and Express

I am currently facing an issue with my node.js API where I have two separate routes set up. One route is for retrieving user data by ID, while the other is a general user endpoint. Here are the routes: app.get('/api/v1/user/:userid', function (r ...

Upon selecting multiple checkboxes, corresponding form fields will be displayed based on shared attributes

When multiple checkboxes are selected by the user, corresponding form fields should appear based on the checkboxes. For example, if both flight and hotel checkboxes are checked, then the full name and last name fields should be displayed while other fields ...

What is the best approach for converting a string containing data into a format suitable for displaying in a series on React

Here's a question that may seem simple, but is a bit of a challenge to explain if you're not familiar with highcharts. Imagine you have a simple block of code like this: ` [{"name":"Name1","data":[{"x":1477621800,"y":114,"name":"Name2"}]` and y ...

The DOMException occurred when attempting to run the 'querySelector' function on the 'Document' object

Currently, I am engaged in a project that was initiated with bootstrap version 4.3.1. I have a keen interest in both JavaScript and HTML coding. <a class="dropdown-item" href="{{ route('user.panel') }}"> User panel </a& ...

Execute the npm command to organize the files in case the specified directory does

I am facing an issue with my npm package.json script that needs to be executed only when the dist folder is not present. Here is the snippet from my package.json: "scripts": { "predev": "! test dist && webpack --config=webpack.dll.config.js } ...