Solved

sending data through JSON to MVC Controller Method

Posted on 2015-02-05
7
132 Views
Last Modified: 2015-02-05
Hi All,

I've trying to send across some data to a MVC model.

The model is calling but the data is null? any ideas what I'm doing wrong here'

var fields = new Array();

                fields.push({
                    "amount": $('#amountSlider').val(),
                    "duration": $('#durationSlider').val(),
                    "security": $('#currentSecuritySlider').val(),
                    "loan": $('#existingLoansSlider').val(),
                    "securityType": $('#securityTypeDropDown').val(),
                    "charge": $('#chargeDropDown').val(),

                    //second page
                    "fullName": $('#fullNameTextBox').val(),
                    "email": $('#emailTextBox').val(),
                    "phone": $('#phoneTextBox').val()
                });

                console.log(fields);
                console.log(JSON.stringify(fields));

                $.ajax({
                    url: "/Home/SendForm",
                    contentType: "application/x-www-form-urlencoded",
                    type: "POST",
                    datatype: "json",
                    data: JSON.stringify(fields),
                    error: function (xmlHttpRequest, errorText, thrownError) {
                        alert(xmlHttpRequest + "|" + errorText + "|" + thrownError);
                    },
                    success: function (data) {
                        alert(data);
                    }
                });

Open in new window


and the method in my home controller

        public class InstantQuote
        {
            public string amount { get; set; }
            public string duration { get; set; }
            public string security { get; set; }
            public string loan { get; set; }
            public string securityType { get; set; }
            public string charge { get; set; }
            public string fullName { get; set; }
            public string email { get; set; }
            public string phone { get; set; }

        }

        [HttpPost]
        public Boolean SendForm(InstantQuote form) {
...
}

Open in new window


When I break into the c# method its showing form contains an object but all the items are set to null?
0
Comment
Question by:flynny
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40591134
What does your action's signature look like?
0
 

Author Comment

by:flynny
ID: 40591145
Thanks fo rthe fast reply.

As above its just  [HttpPost]
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40591146
Your Javascript is passing an array, but your action isn't expecting an array. Change your Javascript to create a new object, and that object will have property names that correspond to the InstantQuote class.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:flynny
ID: 40591159
Thanks Kaufmed,

that worked.

so in order for MVC to convert the JSON to the model it needs to be explicitly sent as an object rather than a stringified array?

how does the ajax know this is the JSON.stringify not the same string?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40591164
No. You need to match the structure between your C# and your Javascript. You can assuredly send an array from Javascript to C#...if your C# expects an array. So you could have alternatively changed your C# to:

[HttpPost]
public Boolean SendForm(InstantQuote[] form) {

Open in new window


If you actually intend on sending an array, then you'd want the above instead. I didn't gather that you actually needed an array.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40591166
Also, IIRC, you shouldn't need to stringify the data in order to send it. Just send the JSON object in the data property of your AJAX call.
0
 

Author Comment

by:flynny
ID: 40591175
Hi KAufmed,

no i dont need an array I was just wondering how it would be able to tell the difference as the JSON.stringify string of both objects would be the same. (mainly for understanding as you solution worked perfectly.

i just did a console output on both sets and I see now that stringifying the array encases it in []

thanks again kaufmed
0

Featured Post

Get HTML5 Certified

Want to be a web developer? You'll need to know HTML. Prepare for HTML5 certification by enrolling in July's Course of the Month! It's free for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

626 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question