Transferring Composite Data Structures from JavaScript to a WCF RESTful Service

Below are the code snippets:

1. The intricate object:

[DataContract]
public class NewUser
{
    [DataMember(Name = "Email")]
    public string Email { get; set; }
    [DataMember(Name = "FirstName")]
    public string FirstName { get; set; }
    [DataMember(Name = "LastName")]
    public string LastName { get; set; }
    [DataMember(Name = "Mobile")]
    public string Mobile { get; set; }
    [DataMember(Name = "UserAddress")]
    public Address UserAddress { get; set; }
}

2. The Operation contract:

[OperationContract]
[WebInvoke(UriTemplate = "/RegisterUser", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST")]
Guid Register(NewUser col);

3. The JS/Angular HTTP POST call:

var newUser = {};

newUser.Email = $scope.col.Email;
newUser.FirstName = $scope.col.FirstName;
newUser.LastName = $scope.col.LastName;
newUser.Mobile = $scope.col.Mobile;
newUser.CityId = $scope.col.UserAddress.CityId;


$http.post(API_URL + "/RegisterUser", { col: newUser }).success(function (response) {
if(response.status=="success" && !response.mailError){
$scope.register = false;
$scope.alert = {type:'success', msg:"You are successfully registered. Please check mail for the password. If you do not see the mail, check spams"};
}else if(response.mailError){
$scope.alert = {type:'warning', msg:'Unable to send mail! please try forgot password next time you need to login'};
}else{
$scope.alert = {type:'danger', msg:response.msg};
}
$scope.loading = false;
});
  1. The Result: The call is successful and the related Register function in the Service is called. However, the NewUser object received has all properties set to NULL.

The values are correct from the JavaScript side, so it seems like there might be a small missing detail between the calls. Any suggestions? My hunch is that I am overlooking something simple but can't seem to pinpoint it at the moment.

Answer №1

Successfully resolved the issue by making a simple adjustment.

Rather than enclosing the user object within a col object, we can directly pass the user object to the service. Therefore, instead of

$http.post(API_URL + "/RegisterUser", { col: newUser }).success(function (response) {

we now use

$http.post(API_URL + "/RegisterUser", newUser).success(function (response) {

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

The command 'ng' is not a valid internal or external command, and it cannot be run as an operable program or batch file on the Mean Stack platform

Hey there, I'm in the process of developing a meanstack application. Every time I try to run 'ng new client' command, it gives me an error saying 'ng' is not recognized as an internal or external command, operable program or batch ...

Storing form data in a JSON file using JavaScript

For a while now, I've been pondering over this issue. My plan involves creating a desktop application with Electron. As a result, I am working on an app using Node.js and Express.js. The project includes a simple app.js file that executes my website&a ...

Retrieve JSON and HTML in an AJAX request

I have multiple pages that heavily rely on JavaScript, particularly for sorting and filtering datasets. These pages typically display a list of intricate items, usually rendered as <li> elements with HTML content. Users can delete, edit, or add item ...

Issue with AngularJS date validation occurring only on the initial attempt

When I use the input type "date" tag, I expect it to validate the date. For example, April cannot have 31 days and so on. However, this validation does not work the first time I set the date as "31-04-2014". If I go back to the date field and change the ...

Unable to trigger jQuery .click event

Having recently delved into the world of AJAX, jQuery, and JavaScript, I am facing a challenge that I believe is rooted in a simple oversight on my part. Expressing this issue can be quite perplexing, but I'll do my utmost to articulate it clearly. I ...

Top spot for placing a file containing a polyfill to ensure cross-browser compatibility in JavaScript projects

Curious about the best location within a React / Redux app (built with create-react-app) to store custom polyfill files for browsers that do not support certain features. I specifically require Array.prototype.includes and String.prototype.startsWith, as ...

Unlocking the Secret: Retrieving Click Event Values from a jQuery Function

Is there a way to retrieve the onclick event value change in jQuery when clicking on a DIV? $("ul li").click(function(){ var newValue = $(this).val(); }); $(function(){ alert(newValue); }); ...

Is there a way to send an Ajax response to the web browser client as a downloadable file?

In my MVC 3 project, I have generated a csv file in an Action Method on the server named GetCSV() which is designated as an [HttpPost] action method. My goal is to send this csv file directly to the web browser for download. While I was able to achieve t ...

Using JavaScript in Node, you can pass an object by throwing a new Error

How can I properly throw an error in my node application and access the properties of the error object? Here is my current code: throw new Error({ status: 400, error: 'Email already exists' }); However, when I do this, I get the following outpu ...

Adjust the opacity of a div's background without impacting the children elements

I am currently working on a dynamic content display in my HTML page using some knockout code. The setup looks like this: <section id="picturesSection" class="background-image" data-bind="foreach: { data: people, as: 'person'}"> <div ...

Using Event Delegation in Practice

I am facing an issue with loading 2 <span> elements from separate ajax scripts onto a webpage upon selection from a dropdown box. Here is a snippet of my code: <span id='room_rate'>1,000</span> // content loaded by one ajax scri ...

My code seems to be malfunctioning - why can't I keep the aspect ratio?

UPDATE: Can someone please assist me with maintaining the aspect ratio of a drawn image? I am struggling to achieve this and would appreciate any help. I have been attempting to upload an image, draw it using the imageDraw() function, and fit it within a ...

Guide to creating a Checkbox List similar to the one found in the Alarm & Clock Application

https://i.sstatic.net/IAjam.png https://i.sstatic.net/NIYNN.png Is there a way to create a list of checkboxes that are aligned to the left of the button they open from, with an opening and closing animation similar to the Alarm & Clock App in Windows 10? ...

What could be causing the Selenium web driver to crash while trying to navigate?

Situation : For our ASP.NET MVC application, we decided to run integration tests using Selenium's Web Driver. Issue : Upon running the tests in VS2015 with Internet Explorer Driver, an error message appears on the console (refer to screenshot below ...

Is there a difference between innerHTML strings and their corresponding strings in JavaScript?

I am facing an issue with a code snippet that seems to have an unusual error. The following code is a simplified version to demonstrate the strange behavior. <html> <head> <script type = "text/javascript"> window.onload = fun ...

Exploring the functionalities of the 'Angular Rails Templates' gem

Recently, I've been exploring the use of the templates folder in AngularJS instead of the traditional 'views' folders found in Rails. Everything runs smoothly when I write my code in HTML, but what if I want to utilize slim for a more conci ...

JavaScript: Generating multiple variables using a for loop?

Is there a way to dynamically create n variables a_1, a_2, a_3 ... a_n, where the value of n is determined during runtime? Attempting to use the following code would not produce the desired outcome: var n = prompt("Enter number of variables?"); for (i= ...

I'm intrigued by this maneuver, but I am uncertain about its safety when used in JavaScript

I am currently contemplating the safety and reliability of assigning a variable within an if statement across different browsers. If it proves to be safe, then I am inclined to proceed with its usage. The scenario involves reading the query string and che ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...