I want to post data in the Mssql Database using Asp.netCore Api and Html Form. I have Added This script to post data.but All the values are coming null
Jquery script in Html File
<script type="text/javascript">
var valdata = $("#formData").serialize();
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
let formData = {};
$("#formData").serializeArray().map((x) => { formData[x.name] = x.value; });
$.ajax({
url: "https://localhost:44389/Register",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " data);
},
error: function (data) {
alert("Error: " data);
}
});
});
});
</script>
.net Core Api
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromBody]CustmRegistration Register)
{
try
{
userInterface.InsertCustomer(Register);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
CodePudding user response:
but All the values are coming null
Where are these values null? my suggestion is to start debugging a bit more thoroughly.
- Have you tried your api function trough postman or a tool likewise?
- Settting breakpoints can be nice to look into your program's data at runtime.
- if these values are null in your database it would be nice to see what
userInterface.InsertCustomer(Register);
does. - Once you know if your .net part is working start debugging your ajaxc call. take a look at the network section of the developer tools form the browser you are using.
If you have collected more data, people can help you more easelly.
CodePudding user response:
1.When you use .serialize()
, it generates the data in a query string
format 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
can work.
2.Also you need move the serialize
method into onclick event.
3.Be sure change [FromBody]
to [FromForm]
.
Here is a whole working demo:
View:
@model CustmRegistration
<form id="formData">
<!--more code-->
<input type="button" id="btnsubmit"value="create" />
</form>
@section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
var valdata = $("#formData").serialize(); //move to here...
$.ajax({
url: "/home/Register",
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " data);
},
error: function (data) {
alert("Error: " data);
}
});
});
});
</script>
}
Controller:
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromForm]CustmRegistration Register)
{ //...}