Serializing form data into a model for an Ajax POST









up vote
0
down vote

favorite












I have an MVC web application, with this model



public class PersonViewModel

public Guid SchoolId get; set;
public string Name get; set;


public class StudentViewModel : PersonViewModel





I have this controller method to take a StudentViewModel and create a Student in my database:



[HttpPost]
public async Task<IActionResult> CreateStudent(StudentViewModel viewModel)

// ... do stuff



I'm doing a lot of dynamic UI stuff with my form, and I might be posting to different endpoints with different values, so I decided to just submit the form using javascript and decide where I'm posting to based on some conditionals.



So that's basically the reason I'm not going the normal route with the strongly typed helper methods - this is what I have in my view:



<form id="form">
<input name="SchoolId" value="@Model.Id" type="hidden" />

<input name="Name" type="text" />

<button type="submit">Create</button>
</form>

<script>

$(document).ready(function ()

$('#form').on('submit', function (e)
e.preventDefault();

var formData = $('#form').serialize()
console.log(formData);

$.ajax(
url: '/CreateStudent',
type: "POST",
data: formData,
contentType: "application/json"
);
);

);

</script>


I can see in my console log that the form data is serialized correctly, and it hits my controller method. But the view model parameter doesn't have the values that I passed to it.



I've tried setting the form data this way:



var formData = JSON.stringify($('#form').serializeArray());


I even tried just hardcoding the values:



var formData = '"SchoolId":"c65fc8ad-7ad2-e811-b37f-9cb6d0b709c2","Name":"Testing"';


But no matter what I try, the view model values don't get set.



Am I formatting the form data wrong? Or is there a different way completely that I need to do this?










share|improve this question























  • Haha wow, I knew it would be something small, spent hours trying to figure that out. Thanks!
    – Steven
    Nov 9 at 22:06














up vote
0
down vote

favorite












I have an MVC web application, with this model



public class PersonViewModel

public Guid SchoolId get; set;
public string Name get; set;


public class StudentViewModel : PersonViewModel





I have this controller method to take a StudentViewModel and create a Student in my database:



[HttpPost]
public async Task<IActionResult> CreateStudent(StudentViewModel viewModel)

// ... do stuff



I'm doing a lot of dynamic UI stuff with my form, and I might be posting to different endpoints with different values, so I decided to just submit the form using javascript and decide where I'm posting to based on some conditionals.



So that's basically the reason I'm not going the normal route with the strongly typed helper methods - this is what I have in my view:



<form id="form">
<input name="SchoolId" value="@Model.Id" type="hidden" />

<input name="Name" type="text" />

<button type="submit">Create</button>
</form>

<script>

$(document).ready(function ()

$('#form').on('submit', function (e)
e.preventDefault();

var formData = $('#form').serialize()
console.log(formData);

$.ajax(
url: '/CreateStudent',
type: "POST",
data: formData,
contentType: "application/json"
);
);

);

</script>


I can see in my console log that the form data is serialized correctly, and it hits my controller method. But the view model parameter doesn't have the values that I passed to it.



I've tried setting the form data this way:



var formData = JSON.stringify($('#form').serializeArray());


I even tried just hardcoding the values:



var formData = '"SchoolId":"c65fc8ad-7ad2-e811-b37f-9cb6d0b709c2","Name":"Testing"';


But no matter what I try, the view model values don't get set.



Am I formatting the form data wrong? Or is there a different way completely that I need to do this?










share|improve this question























  • Haha wow, I knew it would be something small, spent hours trying to figure that out. Thanks!
    – Steven
    Nov 9 at 22:06












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have an MVC web application, with this model



public class PersonViewModel

public Guid SchoolId get; set;
public string Name get; set;


public class StudentViewModel : PersonViewModel





I have this controller method to take a StudentViewModel and create a Student in my database:



[HttpPost]
public async Task<IActionResult> CreateStudent(StudentViewModel viewModel)

// ... do stuff



I'm doing a lot of dynamic UI stuff with my form, and I might be posting to different endpoints with different values, so I decided to just submit the form using javascript and decide where I'm posting to based on some conditionals.



So that's basically the reason I'm not going the normal route with the strongly typed helper methods - this is what I have in my view:



<form id="form">
<input name="SchoolId" value="@Model.Id" type="hidden" />

<input name="Name" type="text" />

<button type="submit">Create</button>
</form>

<script>

$(document).ready(function ()

$('#form').on('submit', function (e)
e.preventDefault();

var formData = $('#form').serialize()
console.log(formData);

$.ajax(
url: '/CreateStudent',
type: "POST",
data: formData,
contentType: "application/json"
);
);

);

</script>


I can see in my console log that the form data is serialized correctly, and it hits my controller method. But the view model parameter doesn't have the values that I passed to it.



I've tried setting the form data this way:



var formData = JSON.stringify($('#form').serializeArray());


I even tried just hardcoding the values:



var formData = '"SchoolId":"c65fc8ad-7ad2-e811-b37f-9cb6d0b709c2","Name":"Testing"';


But no matter what I try, the view model values don't get set.



Am I formatting the form data wrong? Or is there a different way completely that I need to do this?










share|improve this question















I have an MVC web application, with this model



public class PersonViewModel

public Guid SchoolId get; set;
public string Name get; set;


public class StudentViewModel : PersonViewModel





I have this controller method to take a StudentViewModel and create a Student in my database:



[HttpPost]
public async Task<IActionResult> CreateStudent(StudentViewModel viewModel)

// ... do stuff



I'm doing a lot of dynamic UI stuff with my form, and I might be posting to different endpoints with different values, so I decided to just submit the form using javascript and decide where I'm posting to based on some conditionals.



So that's basically the reason I'm not going the normal route with the strongly typed helper methods - this is what I have in my view:



<form id="form">
<input name="SchoolId" value="@Model.Id" type="hidden" />

<input name="Name" type="text" />

<button type="submit">Create</button>
</form>

<script>

$(document).ready(function ()

$('#form').on('submit', function (e)
e.preventDefault();

var formData = $('#form').serialize()
console.log(formData);

$.ajax(
url: '/CreateStudent',
type: "POST",
data: formData,
contentType: "application/json"
);
);

);

</script>


I can see in my console log that the form data is serialized correctly, and it hits my controller method. But the view model parameter doesn't have the values that I passed to it.



I've tried setting the form data this way:



var formData = JSON.stringify($('#form').serializeArray());


I even tried just hardcoding the values:



var formData = '"SchoolId":"c65fc8ad-7ad2-e811-b37f-9cb6d0b709c2","Name":"Testing"';


But no matter what I try, the view model values don't get set.



Am I formatting the form data wrong? Or is there a different way completely that I need to do this?







c# jquery ajax asp.net-core-mvc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 13:33









Tetsuya Yamamoto

13.4k41939




13.4k41939










asked Nov 9 at 21:57









Steven

7,11557153247




7,11557153247











  • Haha wow, I knew it would be something small, spent hours trying to figure that out. Thanks!
    – Steven
    Nov 9 at 22:06
















  • Haha wow, I knew it would be something small, spent hours trying to figure that out. Thanks!
    – Steven
    Nov 9 at 22:06















Haha wow, I knew it would be something small, spent hours trying to figure that out. Thanks!
– Steven
Nov 9 at 22:06




Haha wow, I knew it would be something small, spent hours trying to figure that out. Thanks!
– Steven
Nov 9 at 22:06












1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










When you use .serialize(), it generates the data in a 'query string' format - i.e. SchoolId=someValue&Name=AnotherValue, which needs to be sent using the default contentType which is 'application/x-www-form-urlencoded; charset=UTF-8', not as JSON.



Either remove the contentType option or specify contentType: 'application/x-www-form-urlencoded; charset=UTF-8'



$('#form').on('submit', function (e) 
e.preventDefault();
var formData = $('#form').serialize()
$.ajax(
url: '@Url.Action("CreateStudent")', //recommended
type: "POST",
data: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8' // optional
);
);


Note that if you were to use contentType: "application/json", then you would generate the data using (assumes you give the inputs the appropriate id attribute)



var formData = JSON.stringify(
SchoolId: $('#SchoolId').val(),
Name: $('#Name').val(),
)





share|improve this answer






















  • A nice and clean solution. Just as a side note to OP : Note the line of // recommended . the OP is posting to '/CreateStudent', but it seems that he doesn't define such a named route.
    – itminus
    Nov 12 at 8:53











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53233761%2fserializing-form-data-into-a-model-for-an-ajax-post%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










When you use .serialize(), it generates the data in a 'query string' format - i.e. SchoolId=someValue&Name=AnotherValue, which needs to be sent using the default contentType which is 'application/x-www-form-urlencoded; charset=UTF-8', not as JSON.



Either remove the contentType option or specify contentType: 'application/x-www-form-urlencoded; charset=UTF-8'



$('#form').on('submit', function (e) 
e.preventDefault();
var formData = $('#form').serialize()
$.ajax(
url: '@Url.Action("CreateStudent")', //recommended
type: "POST",
data: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8' // optional
);
);


Note that if you were to use contentType: "application/json", then you would generate the data using (assumes you give the inputs the appropriate id attribute)



var formData = JSON.stringify(
SchoolId: $('#SchoolId').val(),
Name: $('#Name').val(),
)





share|improve this answer






















  • A nice and clean solution. Just as a side note to OP : Note the line of // recommended . the OP is posting to '/CreateStudent', but it seems that he doesn't define such a named route.
    – itminus
    Nov 12 at 8:53















up vote
2
down vote



accepted










When you use .serialize(), it generates the data in a 'query string' format - i.e. SchoolId=someValue&Name=AnotherValue, which needs to be sent using the default contentType which is 'application/x-www-form-urlencoded; charset=UTF-8', not as JSON.



Either remove the contentType option or specify contentType: 'application/x-www-form-urlencoded; charset=UTF-8'



$('#form').on('submit', function (e) 
e.preventDefault();
var formData = $('#form').serialize()
$.ajax(
url: '@Url.Action("CreateStudent")', //recommended
type: "POST",
data: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8' // optional
);
);


Note that if you were to use contentType: "application/json", then you would generate the data using (assumes you give the inputs the appropriate id attribute)



var formData = JSON.stringify(
SchoolId: $('#SchoolId').val(),
Name: $('#Name').val(),
)





share|improve this answer






















  • A nice and clean solution. Just as a side note to OP : Note the line of // recommended . the OP is posting to '/CreateStudent', but it seems that he doesn't define such a named route.
    – itminus
    Nov 12 at 8:53













up vote
2
down vote



accepted







up vote
2
down vote



accepted






When you use .serialize(), it generates the data in a 'query string' format - i.e. SchoolId=someValue&Name=AnotherValue, which needs to be sent using the default contentType which is 'application/x-www-form-urlencoded; charset=UTF-8', not as JSON.



Either remove the contentType option or specify contentType: 'application/x-www-form-urlencoded; charset=UTF-8'



$('#form').on('submit', function (e) 
e.preventDefault();
var formData = $('#form').serialize()
$.ajax(
url: '@Url.Action("CreateStudent")', //recommended
type: "POST",
data: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8' // optional
);
);


Note that if you were to use contentType: "application/json", then you would generate the data using (assumes you give the inputs the appropriate id attribute)



var formData = JSON.stringify(
SchoolId: $('#SchoolId').val(),
Name: $('#Name').val(),
)





share|improve this answer














When you use .serialize(), it generates the data in a 'query string' format - i.e. SchoolId=someValue&Name=AnotherValue, which needs to be sent using the default contentType which is 'application/x-www-form-urlencoded; charset=UTF-8', not as JSON.



Either remove the contentType option or specify contentType: 'application/x-www-form-urlencoded; charset=UTF-8'



$('#form').on('submit', function (e) 
e.preventDefault();
var formData = $('#form').serialize()
$.ajax(
url: '@Url.Action("CreateStudent")', //recommended
type: "POST",
data: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8' // optional
);
);


Note that if you were to use contentType: "application/json", then you would generate the data using (assumes you give the inputs the appropriate id attribute)



var formData = JSON.stringify(
SchoolId: $('#SchoolId').val(),
Name: $('#Name').val(),
)






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 10 at 1:07

























answered Nov 10 at 0:54









Stephen Muecke

97.7k1995119




97.7k1995119











  • A nice and clean solution. Just as a side note to OP : Note the line of // recommended . the OP is posting to '/CreateStudent', but it seems that he doesn't define such a named route.
    – itminus
    Nov 12 at 8:53

















  • A nice and clean solution. Just as a side note to OP : Note the line of // recommended . the OP is posting to '/CreateStudent', but it seems that he doesn't define such a named route.
    – itminus
    Nov 12 at 8:53
















A nice and clean solution. Just as a side note to OP : Note the line of // recommended . the OP is posting to '/CreateStudent', but it seems that he doesn't define such a named route.
– itminus
Nov 12 at 8:53





A nice and clean solution. Just as a side note to OP : Note the line of // recommended . the OP is posting to '/CreateStudent', but it seems that he doesn't define such a named route.
– itminus
Nov 12 at 8:53


















 

draft saved


draft discarded















































 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53233761%2fserializing-form-data-into-a-model-for-an-ajax-post%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Use pre created SQLite database for Android project in kotlin

Darth Vader #20

Ondo