Reputation: 2805
I'm sending Json from Jquery to an Action Controller, but for some reason, the first and the last elements from the Json string are not being received correctly in my action controller, it seems that a curly brace is being added as a value to the last element , and the first element is always null when is a nullable field or if it is an int its value is 0. This is my JQuery code:
$(function () {
$("#myButton").click(function () {
var student= JSON.stringify($("#myForm").serialize());
alert(student);
$.ajax({
type: 'post',
url: $("#myForm").data("url"),
data: JSON.stringify({ 'policy': student}),
success: //more code..
})
I'm using an alert to show the value of the $("#myForm").serialize()
and the values are being set correctly when the alert is executed. The problem is on the way to the action controller. This is what the alert message shows:
"first_field=7.5&aut_id=3456690&..........more info in here no
problem..........&birthday=&last_field="
For that json string
when is received by the Action Controller this is what it get: first_field= null(is a nullable field in my Model)
And last_field = "\\\"\"}"
.It contains 3 escape characters so I imagine that the value is receiving is = \""}
What should be happening??? All the other values that are in the middle are being received correctly, it's just he ones in the edges
This is my action controller:
[HTTPPost]
public ActionResult EditStudent(Student student)
{
//some code...
}
Upvotes: 0
Views: 26
Reputation:
You can just send the data using the serialized data
$.ajax({
....
data: $("#myForm").serialize(),
which will use the default 'application/x-www-form-urlencoded; charset=UTF-8'
for the contentType
If you stringify the data, then you need to also set the contentType
to 'application/json',
so that the DefaultModelBinder
uses the JsonValueProvider
to convert your data, and in that case the format needs to be
$.ajax({
....
data: JSON.stringify($("#myForm").serialize()),
contentType: 'application/json; charset=UTF-8',
Upvotes: 1