How to pass a AJAX Response(true/false) from Controller using ASP .NET CORE
I want to retrieve the response from my ASP.NET Core Controller through AJAX. Here's the example of my code
public IActionResult Submit(ViewModel model) {
var isValid = true;
if (isValid) {
return Json(new {
success = true
});
}
return Json(new {
success = false
});
}
CSHTML part
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
</form>
$("#formSubmit").on('submit', function(e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: formAction,
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function(response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
e.preventDefault();
}
});
});
The problem in this code it redirect/loading to page showing the {"success":false}
.
My ViewModel
public class ViewModel{
public string Name { get; set; }
public string Address { get; set; }
public string JobDescription { get; set; }
}
c# jquery json ajax asp.net-core
|
show 13 more comments
I want to retrieve the response from my ASP.NET Core Controller through AJAX. Here's the example of my code
public IActionResult Submit(ViewModel model) {
var isValid = true;
if (isValid) {
return Json(new {
success = true
});
}
return Json(new {
success = false
});
}
CSHTML part
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
</form>
$("#formSubmit").on('submit', function(e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: formAction,
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function(response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
e.preventDefault();
}
});
});
The problem in this code it redirect/loading to page showing the {"success":false}
.
My ViewModel
public class ViewModel{
public string Name { get; set; }
public string Address { get; set; }
public string JobDescription { get; set; }
}
c# jquery json ajax asp.net-core
2
Try looking in the browser development tools to see exactly what is being returned. Also ajax is asynchronous, and you are calling e.preventDefault() on the success callback
– ste-fu
Nov 20 '18 at 9:29
success value was not being return in success: function (response) { }
– noob101
Nov 20 '18 at 9:33
1
Put thee.preventDefault();
call as the first line of thesubmit
event handler. You're performing it in the callback at the moment, which is too late.,
– Rory McCrossan
Nov 20 '18 at 9:40
1
@RoryMcCrossan thanks, I found out that I'm getting HTTP Error 400 (Bad Request) I already use JSON.stringify, any idea?
– noob101
Nov 20 '18 at 9:55
1
@Liam the formAction value is Home/Submit. see the updated example code above I added var formAction = $(this).attr("action");
– noob101
Nov 20 '18 at 10:09
|
show 13 more comments
I want to retrieve the response from my ASP.NET Core Controller through AJAX. Here's the example of my code
public IActionResult Submit(ViewModel model) {
var isValid = true;
if (isValid) {
return Json(new {
success = true
});
}
return Json(new {
success = false
});
}
CSHTML part
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
</form>
$("#formSubmit").on('submit', function(e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: formAction,
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function(response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
e.preventDefault();
}
});
});
The problem in this code it redirect/loading to page showing the {"success":false}
.
My ViewModel
public class ViewModel{
public string Name { get; set; }
public string Address { get; set; }
public string JobDescription { get; set; }
}
c# jquery json ajax asp.net-core
I want to retrieve the response from my ASP.NET Core Controller through AJAX. Here's the example of my code
public IActionResult Submit(ViewModel model) {
var isValid = true;
if (isValid) {
return Json(new {
success = true
});
}
return Json(new {
success = false
});
}
CSHTML part
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
</form>
$("#formSubmit").on('submit', function(e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: formAction,
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function(response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
e.preventDefault();
}
});
});
The problem in this code it redirect/loading to page showing the {"success":false}
.
My ViewModel
public class ViewModel{
public string Name { get; set; }
public string Address { get; set; }
public string JobDescription { get; set; }
}
c# jquery json ajax asp.net-core
c# jquery json ajax asp.net-core
edited Nov 20 '18 at 12:24
noob101
asked Nov 20 '18 at 9:25
noob101noob101
89
89
2
Try looking in the browser development tools to see exactly what is being returned. Also ajax is asynchronous, and you are calling e.preventDefault() on the success callback
– ste-fu
Nov 20 '18 at 9:29
success value was not being return in success: function (response) { }
– noob101
Nov 20 '18 at 9:33
1
Put thee.preventDefault();
call as the first line of thesubmit
event handler. You're performing it in the callback at the moment, which is too late.,
– Rory McCrossan
Nov 20 '18 at 9:40
1
@RoryMcCrossan thanks, I found out that I'm getting HTTP Error 400 (Bad Request) I already use JSON.stringify, any idea?
– noob101
Nov 20 '18 at 9:55
1
@Liam the formAction value is Home/Submit. see the updated example code above I added var formAction = $(this).attr("action");
– noob101
Nov 20 '18 at 10:09
|
show 13 more comments
2
Try looking in the browser development tools to see exactly what is being returned. Also ajax is asynchronous, and you are calling e.preventDefault() on the success callback
– ste-fu
Nov 20 '18 at 9:29
success value was not being return in success: function (response) { }
– noob101
Nov 20 '18 at 9:33
1
Put thee.preventDefault();
call as the first line of thesubmit
event handler. You're performing it in the callback at the moment, which is too late.,
– Rory McCrossan
Nov 20 '18 at 9:40
1
@RoryMcCrossan thanks, I found out that I'm getting HTTP Error 400 (Bad Request) I already use JSON.stringify, any idea?
– noob101
Nov 20 '18 at 9:55
1
@Liam the formAction value is Home/Submit. see the updated example code above I added var formAction = $(this).attr("action");
– noob101
Nov 20 '18 at 10:09
2
2
Try looking in the browser development tools to see exactly what is being returned. Also ajax is asynchronous, and you are calling e.preventDefault() on the success callback
– ste-fu
Nov 20 '18 at 9:29
Try looking in the browser development tools to see exactly what is being returned. Also ajax is asynchronous, and you are calling e.preventDefault() on the success callback
– ste-fu
Nov 20 '18 at 9:29
success value was not being return in success: function (response) { }
– noob101
Nov 20 '18 at 9:33
success value was not being return in success: function (response) { }
– noob101
Nov 20 '18 at 9:33
1
1
Put the
e.preventDefault();
call as the first line of the submit
event handler. You're performing it in the callback at the moment, which is too late.,– Rory McCrossan
Nov 20 '18 at 9:40
Put the
e.preventDefault();
call as the first line of the submit
event handler. You're performing it in the callback at the moment, which is too late.,– Rory McCrossan
Nov 20 '18 at 9:40
1
1
@RoryMcCrossan thanks, I found out that I'm getting HTTP Error 400 (Bad Request) I already use JSON.stringify, any idea?
– noob101
Nov 20 '18 at 9:55
@RoryMcCrossan thanks, I found out that I'm getting HTTP Error 400 (Bad Request) I already use JSON.stringify, any idea?
– noob101
Nov 20 '18 at 9:55
1
1
@Liam the formAction value is Home/Submit. see the updated example code above I added var formAction = $(this).attr("action");
– noob101
Nov 20 '18 at 10:09
@Liam the formAction value is Home/Submit. see the updated example code above I added var formAction = $(this).attr("action");
– noob101
Nov 20 '18 at 10:09
|
show 13 more comments
2 Answers
2
active
oldest
votes
it seems there are a few issues present here
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
You are specifying asp-action and asp-controller. Omit all of these properties. Start with just:
<form>...</form>
The reason being, when you set those attributes it uses the old-school form submission mechanism which redirects (one of the side affects you listed).
Also the name type seems to be a mismatch, you use ViewModel
but in your example the type name is TFAViewModel
Try the following, above your controller (for each method) or above the method itself add
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit([FromBody]ViewModel model)
{
ModelState.IsValid; //use to inspect. You will also see any violations
....
}
In your JS code ensure to do the following (as has been commented)
e.preventDefault(); //stops redirect
sorry for the late response. I tried the solution that you gave and now I'm getting HTTP Error 401 (Unauthorized error).
– noob101
Nov 20 '18 at 12:23
1
OK. Add [AllowAnonymous] as another attribute above Consumes. It's always a good sign when your errors are changing. Means something is progressing and you're closer to your solution. You may have some default [Authorize] attribute somewhere. Just also ensure you aren't requiring an anti-forgery token either
– Neal
Nov 20 '18 at 12:37
Yes, I'm using [Authorize] attribute. I put [AllowAnonymous] as you said but I'm still getting HTTP Error 400 (Bad Request) and I tried to put [ValidateAntiForgeryToken] and still getting HTTP Error 400 (Bad Request).
– noob101
Nov 20 '18 at 13:03
Cool, allow anonymous prevents 401 (Unauthorized). Now you have 400 Bad request. Which means that your modelstate is invalid. Like I proposed in the answer, add a breakpoint in the first line and inspect ModelState. Most likely ModelState.IsValid = false, and you have a violation. You can inspect violations in ModelState.Values. I have also noticed you sending TitleCaseFromJavascript. This is incorrect, you need to send camelCase (it should auto resolve between C# convention and JS convention) Good luck.
– Neal
Nov 20 '18 at 13:07
If you have issues with the camelCase TitleCase mapping add this to your startup file services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
– Neal
Nov 20 '18 at 13:08
|
show 1 more comment
Have you use [HttpPost]
attribute on the Submit action? You need to set a specific url like "/Home/Submit" and have a reference to jquery.
Action:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit(ViewModel model)
{
var isValid = true;
if (isValid)
{
return Json(new
{
success = true
});
}
return Json(new
{
success = false
});
}
View:
<form id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
<input type="submit" value="Create" class="btn btn-default" />
</form>
@section Scripts{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$("#formSubmit").on('submit', function (e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
e.preventDefault();
//var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: "/Home/Submit",
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function (response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
// e.preventDefault();
}
}
});
});
</script>
}
add a comment |
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',
autoActivateHeartbeat: false,
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389844%2fhow-to-pass-a-ajax-responsetrue-false-from-controller-using-asp-net-core%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
it seems there are a few issues present here
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
You are specifying asp-action and asp-controller. Omit all of these properties. Start with just:
<form>...</form>
The reason being, when you set those attributes it uses the old-school form submission mechanism which redirects (one of the side affects you listed).
Also the name type seems to be a mismatch, you use ViewModel
but in your example the type name is TFAViewModel
Try the following, above your controller (for each method) or above the method itself add
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit([FromBody]ViewModel model)
{
ModelState.IsValid; //use to inspect. You will also see any violations
....
}
In your JS code ensure to do the following (as has been commented)
e.preventDefault(); //stops redirect
sorry for the late response. I tried the solution that you gave and now I'm getting HTTP Error 401 (Unauthorized error).
– noob101
Nov 20 '18 at 12:23
1
OK. Add [AllowAnonymous] as another attribute above Consumes. It's always a good sign when your errors are changing. Means something is progressing and you're closer to your solution. You may have some default [Authorize] attribute somewhere. Just also ensure you aren't requiring an anti-forgery token either
– Neal
Nov 20 '18 at 12:37
Yes, I'm using [Authorize] attribute. I put [AllowAnonymous] as you said but I'm still getting HTTP Error 400 (Bad Request) and I tried to put [ValidateAntiForgeryToken] and still getting HTTP Error 400 (Bad Request).
– noob101
Nov 20 '18 at 13:03
Cool, allow anonymous prevents 401 (Unauthorized). Now you have 400 Bad request. Which means that your modelstate is invalid. Like I proposed in the answer, add a breakpoint in the first line and inspect ModelState. Most likely ModelState.IsValid = false, and you have a violation. You can inspect violations in ModelState.Values. I have also noticed you sending TitleCaseFromJavascript. This is incorrect, you need to send camelCase (it should auto resolve between C# convention and JS convention) Good luck.
– Neal
Nov 20 '18 at 13:07
If you have issues with the camelCase TitleCase mapping add this to your startup file services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
– Neal
Nov 20 '18 at 13:08
|
show 1 more comment
it seems there are a few issues present here
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
You are specifying asp-action and asp-controller. Omit all of these properties. Start with just:
<form>...</form>
The reason being, when you set those attributes it uses the old-school form submission mechanism which redirects (one of the side affects you listed).
Also the name type seems to be a mismatch, you use ViewModel
but in your example the type name is TFAViewModel
Try the following, above your controller (for each method) or above the method itself add
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit([FromBody]ViewModel model)
{
ModelState.IsValid; //use to inspect. You will also see any violations
....
}
In your JS code ensure to do the following (as has been commented)
e.preventDefault(); //stops redirect
sorry for the late response. I tried the solution that you gave and now I'm getting HTTP Error 401 (Unauthorized error).
– noob101
Nov 20 '18 at 12:23
1
OK. Add [AllowAnonymous] as another attribute above Consumes. It's always a good sign when your errors are changing. Means something is progressing and you're closer to your solution. You may have some default [Authorize] attribute somewhere. Just also ensure you aren't requiring an anti-forgery token either
– Neal
Nov 20 '18 at 12:37
Yes, I'm using [Authorize] attribute. I put [AllowAnonymous] as you said but I'm still getting HTTP Error 400 (Bad Request) and I tried to put [ValidateAntiForgeryToken] and still getting HTTP Error 400 (Bad Request).
– noob101
Nov 20 '18 at 13:03
Cool, allow anonymous prevents 401 (Unauthorized). Now you have 400 Bad request. Which means that your modelstate is invalid. Like I proposed in the answer, add a breakpoint in the first line and inspect ModelState. Most likely ModelState.IsValid = false, and you have a violation. You can inspect violations in ModelState.Values. I have also noticed you sending TitleCaseFromJavascript. This is incorrect, you need to send camelCase (it should auto resolve between C# convention and JS convention) Good luck.
– Neal
Nov 20 '18 at 13:07
If you have issues with the camelCase TitleCase mapping add this to your startup file services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
– Neal
Nov 20 '18 at 13:08
|
show 1 more comment
it seems there are a few issues present here
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
You are specifying asp-action and asp-controller. Omit all of these properties. Start with just:
<form>...</form>
The reason being, when you set those attributes it uses the old-school form submission mechanism which redirects (one of the side affects you listed).
Also the name type seems to be a mismatch, you use ViewModel
but in your example the type name is TFAViewModel
Try the following, above your controller (for each method) or above the method itself add
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit([FromBody]ViewModel model)
{
ModelState.IsValid; //use to inspect. You will also see any violations
....
}
In your JS code ensure to do the following (as has been commented)
e.preventDefault(); //stops redirect
it seems there are a few issues present here
<form asp-action="Submit" asp-controller="Home" id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
You are specifying asp-action and asp-controller. Omit all of these properties. Start with just:
<form>...</form>
The reason being, when you set those attributes it uses the old-school form submission mechanism which redirects (one of the side affects you listed).
Also the name type seems to be a mismatch, you use ViewModel
but in your example the type name is TFAViewModel
Try the following, above your controller (for each method) or above the method itself add
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit([FromBody]ViewModel model)
{
ModelState.IsValid; //use to inspect. You will also see any violations
....
}
In your JS code ensure to do the following (as has been commented)
e.preventDefault(); //stops redirect
answered Nov 20 '18 at 11:13


NealNeal
298111
298111
sorry for the late response. I tried the solution that you gave and now I'm getting HTTP Error 401 (Unauthorized error).
– noob101
Nov 20 '18 at 12:23
1
OK. Add [AllowAnonymous] as another attribute above Consumes. It's always a good sign when your errors are changing. Means something is progressing and you're closer to your solution. You may have some default [Authorize] attribute somewhere. Just also ensure you aren't requiring an anti-forgery token either
– Neal
Nov 20 '18 at 12:37
Yes, I'm using [Authorize] attribute. I put [AllowAnonymous] as you said but I'm still getting HTTP Error 400 (Bad Request) and I tried to put [ValidateAntiForgeryToken] and still getting HTTP Error 400 (Bad Request).
– noob101
Nov 20 '18 at 13:03
Cool, allow anonymous prevents 401 (Unauthorized). Now you have 400 Bad request. Which means that your modelstate is invalid. Like I proposed in the answer, add a breakpoint in the first line and inspect ModelState. Most likely ModelState.IsValid = false, and you have a violation. You can inspect violations in ModelState.Values. I have also noticed you sending TitleCaseFromJavascript. This is incorrect, you need to send camelCase (it should auto resolve between C# convention and JS convention) Good luck.
– Neal
Nov 20 '18 at 13:07
If you have issues with the camelCase TitleCase mapping add this to your startup file services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
– Neal
Nov 20 '18 at 13:08
|
show 1 more comment
sorry for the late response. I tried the solution that you gave and now I'm getting HTTP Error 401 (Unauthorized error).
– noob101
Nov 20 '18 at 12:23
1
OK. Add [AllowAnonymous] as another attribute above Consumes. It's always a good sign when your errors are changing. Means something is progressing and you're closer to your solution. You may have some default [Authorize] attribute somewhere. Just also ensure you aren't requiring an anti-forgery token either
– Neal
Nov 20 '18 at 12:37
Yes, I'm using [Authorize] attribute. I put [AllowAnonymous] as you said but I'm still getting HTTP Error 400 (Bad Request) and I tried to put [ValidateAntiForgeryToken] and still getting HTTP Error 400 (Bad Request).
– noob101
Nov 20 '18 at 13:03
Cool, allow anonymous prevents 401 (Unauthorized). Now you have 400 Bad request. Which means that your modelstate is invalid. Like I proposed in the answer, add a breakpoint in the first line and inspect ModelState. Most likely ModelState.IsValid = false, and you have a violation. You can inspect violations in ModelState.Values. I have also noticed you sending TitleCaseFromJavascript. This is incorrect, you need to send camelCase (it should auto resolve between C# convention and JS convention) Good luck.
– Neal
Nov 20 '18 at 13:07
If you have issues with the camelCase TitleCase mapping add this to your startup file services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
– Neal
Nov 20 '18 at 13:08
sorry for the late response. I tried the solution that you gave and now I'm getting HTTP Error 401 (Unauthorized error).
– noob101
Nov 20 '18 at 12:23
sorry for the late response. I tried the solution that you gave and now I'm getting HTTP Error 401 (Unauthorized error).
– noob101
Nov 20 '18 at 12:23
1
1
OK. Add [AllowAnonymous] as another attribute above Consumes. It's always a good sign when your errors are changing. Means something is progressing and you're closer to your solution. You may have some default [Authorize] attribute somewhere. Just also ensure you aren't requiring an anti-forgery token either
– Neal
Nov 20 '18 at 12:37
OK. Add [AllowAnonymous] as another attribute above Consumes. It's always a good sign when your errors are changing. Means something is progressing and you're closer to your solution. You may have some default [Authorize] attribute somewhere. Just also ensure you aren't requiring an anti-forgery token either
– Neal
Nov 20 '18 at 12:37
Yes, I'm using [Authorize] attribute. I put [AllowAnonymous] as you said but I'm still getting HTTP Error 400 (Bad Request) and I tried to put [ValidateAntiForgeryToken] and still getting HTTP Error 400 (Bad Request).
– noob101
Nov 20 '18 at 13:03
Yes, I'm using [Authorize] attribute. I put [AllowAnonymous] as you said but I'm still getting HTTP Error 400 (Bad Request) and I tried to put [ValidateAntiForgeryToken] and still getting HTTP Error 400 (Bad Request).
– noob101
Nov 20 '18 at 13:03
Cool, allow anonymous prevents 401 (Unauthorized). Now you have 400 Bad request. Which means that your modelstate is invalid. Like I proposed in the answer, add a breakpoint in the first line and inspect ModelState. Most likely ModelState.IsValid = false, and you have a violation. You can inspect violations in ModelState.Values. I have also noticed you sending TitleCaseFromJavascript. This is incorrect, you need to send camelCase (it should auto resolve between C# convention and JS convention) Good luck.
– Neal
Nov 20 '18 at 13:07
Cool, allow anonymous prevents 401 (Unauthorized). Now you have 400 Bad request. Which means that your modelstate is invalid. Like I proposed in the answer, add a breakpoint in the first line and inspect ModelState. Most likely ModelState.IsValid = false, and you have a violation. You can inspect violations in ModelState.Values. I have also noticed you sending TitleCaseFromJavascript. This is incorrect, you need to send camelCase (it should auto resolve between C# convention and JS convention) Good luck.
– Neal
Nov 20 '18 at 13:07
If you have issues with the camelCase TitleCase mapping add this to your startup file services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
– Neal
Nov 20 '18 at 13:08
If you have issues with the camelCase TitleCase mapping add this to your startup file services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); })
– Neal
Nov 20 '18 at 13:08
|
show 1 more comment
Have you use [HttpPost]
attribute on the Submit action? You need to set a specific url like "/Home/Submit" and have a reference to jquery.
Action:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit(ViewModel model)
{
var isValid = true;
if (isValid)
{
return Json(new
{
success = true
});
}
return Json(new
{
success = false
});
}
View:
<form id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
<input type="submit" value="Create" class="btn btn-default" />
</form>
@section Scripts{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$("#formSubmit").on('submit', function (e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
e.preventDefault();
//var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: "/Home/Submit",
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function (response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
// e.preventDefault();
}
}
});
});
</script>
}
add a comment |
Have you use [HttpPost]
attribute on the Submit action? You need to set a specific url like "/Home/Submit" and have a reference to jquery.
Action:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit(ViewModel model)
{
var isValid = true;
if (isValid)
{
return Json(new
{
success = true
});
}
return Json(new
{
success = false
});
}
View:
<form id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
<input type="submit" value="Create" class="btn btn-default" />
</form>
@section Scripts{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$("#formSubmit").on('submit', function (e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
e.preventDefault();
//var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: "/Home/Submit",
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function (response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
// e.preventDefault();
}
}
});
});
</script>
}
add a comment |
Have you use [HttpPost]
attribute on the Submit action? You need to set a specific url like "/Home/Submit" and have a reference to jquery.
Action:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit(ViewModel model)
{
var isValid = true;
if (isValid)
{
return Json(new
{
success = true
});
}
return Json(new
{
success = false
});
}
View:
<form id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
<input type="submit" value="Create" class="btn btn-default" />
</form>
@section Scripts{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$("#formSubmit").on('submit', function (e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
e.preventDefault();
//var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: "/Home/Submit",
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function (response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
// e.preventDefault();
}
}
});
});
</script>
}
Have you use [HttpPost]
attribute on the Submit action? You need to set a specific url like "/Home/Submit" and have a reference to jquery.
Action:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public IActionResult Submit(ViewModel model)
{
var isValid = true;
if (isValid)
{
return Json(new
{
success = true
});
}
return Json(new
{
success = false
});
}
View:
<form id="formSubmit" name="formSubmit" method="post" enctype="multipart/form-data">
<input type="text" id="Name" name="Name">
<input type="text" id="Address" name="Address">
<input type="text" id="JobDescription" name="JobDescription">
<input type="submit" value="Create" class="btn btn-default" />
</form>
@section Scripts{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$("#formSubmit").on('submit', function (e) {
var datas = {
Name: $("input[name='Name']").val(),
Address: $("input[name='Address']").val(),
JobDescription: $("input[name='JobDescription']").val()
};
e.preventDefault();
//var formAction = $(this).attr("action");
$.ajax({
method: "POST",
url: "/Home/Submit",
data: JSON.stringify(datas),
dataType: "json",
contentType: 'application/json',
success: function (response) {
if (response.success) {
alert("Test");
return true;
} else {
alert("Invalid/Error");
// e.preventDefault();
}
}
});
});
</script>
}
answered Nov 21 '18 at 2:38


Xing ZouXing Zou
4795
4795
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389844%2fhow-to-pass-a-ajax-responsetrue-false-from-controller-using-asp-net-core%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
2
Try looking in the browser development tools to see exactly what is being returned. Also ajax is asynchronous, and you are calling e.preventDefault() on the success callback
– ste-fu
Nov 20 '18 at 9:29
success value was not being return in success: function (response) { }
– noob101
Nov 20 '18 at 9:33
1
Put the
e.preventDefault();
call as the first line of thesubmit
event handler. You're performing it in the callback at the moment, which is too late.,– Rory McCrossan
Nov 20 '18 at 9:40
1
@RoryMcCrossan thanks, I found out that I'm getting HTTP Error 400 (Bad Request) I already use JSON.stringify, any idea?
– noob101
Nov 20 '18 at 9:55
1
@Liam the formAction value is Home/Submit. see the updated example code above I added var formAction = $(this).attr("action");
– noob101
Nov 20 '18 at 10:09