Why my ajax/fetch call does not work with no Route in my controller?
I spent already long hours on the issue and I can not understand why my jquery ajax post does not work with SurveyController.cs:
[HttpPost]
public ActionResult AddComment(Survey survey)
{
if (survey == null)
{
return NotFound();
}
if (survey != null)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
}
return null;
}
Ajax:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: queryParams,
contentType: "application/json; charset=utf-8",
dataType: "html"
});
Routung from Startup.cs:
app.UseMvc(routes => {
routes.MapRoute(name: "Error", template: "Error",
defaults: new { controller = "Error", action = "Error" });
routes.MapRoute(
name: "default", template: "{controller}/{action}/{id?}",
defaults: new { controller = "MyProjects", action = "Index" });
});
It gives me no errors in the console, but does not hit any breakpoints in the controller.
It works only when I use [Route("comments/new")] in my controller and url: "/comments/new/AddComment", in my Ajax.
I need to use [HttpPost] for the controller to be able to use [ValidateAntiForgeryToken], I think so. But anyway, my Ajax and Controller are according to most of the popular examples for Ajax post that I could find here, and I have no idea why it doeas not work.
EDIT:
I tryed achieve the same with Fetch call:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
fetch(`/comments/new?`,
{
method: 'POST',
body: JSON.stringify({ queryParams }), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
With the same result.
What I noticed, in XHR in console logs, call type is GET not POST, same for AJAX call. Why?
UPDATE:
Because of some reason, when change
fetch(/comments/new?
to
fetch(/Survey/AddComment
XHR gives me still the same call URL:
http://localhost:58256/comments/new?Name=aaa&Change=aaa&Opinion=good
Whatever I wite over there, it does not change!!!(?).
UPDATE:
After removing [Route("comments/new")] and leaving fetch("/Survey/AddComment" there is no call at all.
UPDATE
After clearing whole browser's data, and using:
controller:
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey)
{
if (survey == null)
{
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
Fetch:
const data = {
Name: this.state.surveyState.name,
Change: this.state.surveyState.change,
Opinion: this.state.surveyState.opinion
};
fetch("/Survey/AddComment",
{
method: 'POST',
body: JSON.stringify({ data}), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
I am still getting XHR log for call URL:
http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good
Why?
c# ajax asp.net-core-mvc
add a comment |
I spent already long hours on the issue and I can not understand why my jquery ajax post does not work with SurveyController.cs:
[HttpPost]
public ActionResult AddComment(Survey survey)
{
if (survey == null)
{
return NotFound();
}
if (survey != null)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
}
return null;
}
Ajax:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: queryParams,
contentType: "application/json; charset=utf-8",
dataType: "html"
});
Routung from Startup.cs:
app.UseMvc(routes => {
routes.MapRoute(name: "Error", template: "Error",
defaults: new { controller = "Error", action = "Error" });
routes.MapRoute(
name: "default", template: "{controller}/{action}/{id?}",
defaults: new { controller = "MyProjects", action = "Index" });
});
It gives me no errors in the console, but does not hit any breakpoints in the controller.
It works only when I use [Route("comments/new")] in my controller and url: "/comments/new/AddComment", in my Ajax.
I need to use [HttpPost] for the controller to be able to use [ValidateAntiForgeryToken], I think so. But anyway, my Ajax and Controller are according to most of the popular examples for Ajax post that I could find here, and I have no idea why it doeas not work.
EDIT:
I tryed achieve the same with Fetch call:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
fetch(`/comments/new?`,
{
method: 'POST',
body: JSON.stringify({ queryParams }), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
With the same result.
What I noticed, in XHR in console logs, call type is GET not POST, same for AJAX call. Why?
UPDATE:
Because of some reason, when change
fetch(/comments/new?
to
fetch(/Survey/AddComment
XHR gives me still the same call URL:
http://localhost:58256/comments/new?Name=aaa&Change=aaa&Opinion=good
Whatever I wite over there, it does not change!!!(?).
UPDATE:
After removing [Route("comments/new")] and leaving fetch("/Survey/AddComment" there is no call at all.
UPDATE
After clearing whole browser's data, and using:
controller:
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey)
{
if (survey == null)
{
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
Fetch:
const data = {
Name: this.state.surveyState.name,
Change: this.state.surveyState.change,
Opinion: this.state.surveyState.opinion
};
fetch("/Survey/AddComment",
{
method: 'POST',
body: JSON.stringify({ data}), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
I am still getting XHR log for call URL:
http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good
Why?
c# ajax asp.net-core-mvc
It would help if you add the class Attributes, the class name of the controller (SurveyController???], the Attributes of the action AddComment() and perhaps the routing definition of your Startup.cs to the example. Of course if you want to handle a POST you have to use the Attribute HttpPost.
– koalabruder
Nov 25 '18 at 21:33
@koalabruder updated
– Przemyslaw.Pszemek
Nov 25 '18 at 21:37
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
add a comment |
I spent already long hours on the issue and I can not understand why my jquery ajax post does not work with SurveyController.cs:
[HttpPost]
public ActionResult AddComment(Survey survey)
{
if (survey == null)
{
return NotFound();
}
if (survey != null)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
}
return null;
}
Ajax:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: queryParams,
contentType: "application/json; charset=utf-8",
dataType: "html"
});
Routung from Startup.cs:
app.UseMvc(routes => {
routes.MapRoute(name: "Error", template: "Error",
defaults: new { controller = "Error", action = "Error" });
routes.MapRoute(
name: "default", template: "{controller}/{action}/{id?}",
defaults: new { controller = "MyProjects", action = "Index" });
});
It gives me no errors in the console, but does not hit any breakpoints in the controller.
It works only when I use [Route("comments/new")] in my controller and url: "/comments/new/AddComment", in my Ajax.
I need to use [HttpPost] for the controller to be able to use [ValidateAntiForgeryToken], I think so. But anyway, my Ajax and Controller are according to most of the popular examples for Ajax post that I could find here, and I have no idea why it doeas not work.
EDIT:
I tryed achieve the same with Fetch call:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
fetch(`/comments/new?`,
{
method: 'POST',
body: JSON.stringify({ queryParams }), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
With the same result.
What I noticed, in XHR in console logs, call type is GET not POST, same for AJAX call. Why?
UPDATE:
Because of some reason, when change
fetch(/comments/new?
to
fetch(/Survey/AddComment
XHR gives me still the same call URL:
http://localhost:58256/comments/new?Name=aaa&Change=aaa&Opinion=good
Whatever I wite over there, it does not change!!!(?).
UPDATE:
After removing [Route("comments/new")] and leaving fetch("/Survey/AddComment" there is no call at all.
UPDATE
After clearing whole browser's data, and using:
controller:
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey)
{
if (survey == null)
{
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
Fetch:
const data = {
Name: this.state.surveyState.name,
Change: this.state.surveyState.change,
Opinion: this.state.surveyState.opinion
};
fetch("/Survey/AddComment",
{
method: 'POST',
body: JSON.stringify({ data}), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
I am still getting XHR log for call URL:
http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good
Why?
c# ajax asp.net-core-mvc
I spent already long hours on the issue and I can not understand why my jquery ajax post does not work with SurveyController.cs:
[HttpPost]
public ActionResult AddComment(Survey survey)
{
if (survey == null)
{
return NotFound();
}
if (survey != null)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
}
return null;
}
Ajax:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: queryParams,
contentType: "application/json; charset=utf-8",
dataType: "html"
});
Routung from Startup.cs:
app.UseMvc(routes => {
routes.MapRoute(name: "Error", template: "Error",
defaults: new { controller = "Error", action = "Error" });
routes.MapRoute(
name: "default", template: "{controller}/{action}/{id?}",
defaults: new { controller = "MyProjects", action = "Index" });
});
It gives me no errors in the console, but does not hit any breakpoints in the controller.
It works only when I use [Route("comments/new")] in my controller and url: "/comments/new/AddComment", in my Ajax.
I need to use [HttpPost] for the controller to be able to use [ValidateAntiForgeryToken], I think so. But anyway, my Ajax and Controller are according to most of the popular examples for Ajax post that I could find here, and I have no idea why it doeas not work.
EDIT:
I tryed achieve the same with Fetch call:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
fetch(`/comments/new?`,
{
method: 'POST',
body: JSON.stringify({ queryParams }), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
With the same result.
What I noticed, in XHR in console logs, call type is GET not POST, same for AJAX call. Why?
UPDATE:
Because of some reason, when change
fetch(/comments/new?
to
fetch(/Survey/AddComment
XHR gives me still the same call URL:
http://localhost:58256/comments/new?Name=aaa&Change=aaa&Opinion=good
Whatever I wite over there, it does not change!!!(?).
UPDATE:
After removing [Route("comments/new")] and leaving fetch("/Survey/AddComment" there is no call at all.
UPDATE
After clearing whole browser's data, and using:
controller:
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey)
{
if (survey == null)
{
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
Fetch:
const data = {
Name: this.state.surveyState.name,
Change: this.state.surveyState.change,
Opinion: this.state.surveyState.opinion
};
fetch("/Survey/AddComment",
{
method: 'POST',
body: JSON.stringify({ data}), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
I am still getting XHR log for call URL:
http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good
Why?
c# ajax asp.net-core-mvc
c# ajax asp.net-core-mvc
edited Nov 26 '18 at 12:24
Przemyslaw.Pszemek
asked Nov 25 '18 at 20:33
Przemyslaw.PszemekPrzemyslaw.Pszemek
112111
112111
It would help if you add the class Attributes, the class name of the controller (SurveyController???], the Attributes of the action AddComment() and perhaps the routing definition of your Startup.cs to the example. Of course if you want to handle a POST you have to use the Attribute HttpPost.
– koalabruder
Nov 25 '18 at 21:33
@koalabruder updated
– Przemyslaw.Pszemek
Nov 25 '18 at 21:37
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
add a comment |
It would help if you add the class Attributes, the class name of the controller (SurveyController???], the Attributes of the action AddComment() and perhaps the routing definition of your Startup.cs to the example. Of course if you want to handle a POST you have to use the Attribute HttpPost.
– koalabruder
Nov 25 '18 at 21:33
@koalabruder updated
– Przemyslaw.Pszemek
Nov 25 '18 at 21:37
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
It would help if you add the class Attributes, the class name of the controller (SurveyController???], the Attributes of the action AddComment() and perhaps the routing definition of your Startup.cs to the example. Of course if you want to handle a POST you have to use the Attribute HttpPost.
– koalabruder
Nov 25 '18 at 21:33
It would help if you add the class Attributes, the class name of the controller (SurveyController???], the Attributes of the action AddComment() and perhaps the routing definition of your Startup.cs to the example. Of course if you want to handle a POST you have to use the Attribute HttpPost.
– koalabruder
Nov 25 '18 at 21:33
@koalabruder updated
– Przemyslaw.Pszemek
Nov 25 '18 at 21:37
@koalabruder updated
– Przemyslaw.Pszemek
Nov 25 '18 at 21:37
I tryed it again with fetch call, with same result (please see edited question). What I noticed, in
XHR console logs call type is GET, not POST, also for ajax call. I do not understand why?– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
I tryed it again with fetch call, with same result (please see edited question). What I noticed, in
XHR console logs call type is GET, not POST, also for ajax call. I do not understand why?– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
add a comment |
2 Answers
2
active
oldest
votes
Client side says it is sending application/json, But
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
Is not JSON. Looks more like data you would send in a query string.
Construct a valid JSON payload
const data = {
Name: ${this.state.surveyState.name},
Change: ${this.state.surveyState.change},
Opinion: ${this.state.surveyState.opinion}
};
And send it in the correct format to the server
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Finally, let the Server action know to expect the data in the body of the request by using [FromBody]
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey) {
if (survey == null) {
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
I did like you posted, and nothing hits the break points inside ofpublic IActionResult AddComment([FromBody]Survey survey)
– Przemyslaw.Pszemek
Nov 25 '18 at 22:27
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
@Przemyslaw.Pszemek in your update you still appear to be sending the data incorrectly. Review my answer carefully and notice how I construct the data to be sent.
– Nkosi
Nov 26 '18 at 11:07
@I tryed your approach, please see latest UPDATE on the question. Because of some reason, I am getting inXHRlogs old URL:http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good, even after changing Fetch URL to:/Survey/AddComment. I have the same result also with using format:${this.state.surveyState.name}for the properties.
– Przemyslaw.Pszemek
Nov 26 '18 at 12:12
P.S. Do you think, that does it matter, that Fetch is called by React app?
– Przemyslaw.Pszemek
Nov 26 '18 at 14:35
|
show 1 more comment
The line
name: "default", template: "{controller}/{action}/{id?}",
means that the path /Survey/AddComment will call the Action
SurveyController.AddComment()
The id marked with "?" is optional ({id?}).
If you want to define the route in the Controller you can do something like the following.
[Route("[controller]/[action]")]
public class SurveyController : Controller {
[HttpPost]
public ActionResult AddComment(Survey survey)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Content("Added");
}
}
In both cases you have to mark the Action with [HttpPost] if you send a POST request.
I did like you proposed, and it does not go throu the action, because of some reason
– Przemyslaw.Pszemek
Nov 25 '18 at 22:11
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%2f53471658%2fwhy-my-ajax-fetch-call-does-not-work-with-no-route-in-my-controller%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
Client side says it is sending application/json, But
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
Is not JSON. Looks more like data you would send in a query string.
Construct a valid JSON payload
const data = {
Name: ${this.state.surveyState.name},
Change: ${this.state.surveyState.change},
Opinion: ${this.state.surveyState.opinion}
};
And send it in the correct format to the server
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Finally, let the Server action know to expect the data in the body of the request by using [FromBody]
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey) {
if (survey == null) {
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
I did like you posted, and nothing hits the break points inside ofpublic IActionResult AddComment([FromBody]Survey survey)
– Przemyslaw.Pszemek
Nov 25 '18 at 22:27
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
@Przemyslaw.Pszemek in your update you still appear to be sending the data incorrectly. Review my answer carefully and notice how I construct the data to be sent.
– Nkosi
Nov 26 '18 at 11:07
@I tryed your approach, please see latest UPDATE on the question. Because of some reason, I am getting inXHRlogs old URL:http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good, even after changing Fetch URL to:/Survey/AddComment. I have the same result also with using format:${this.state.surveyState.name}for the properties.
– Przemyslaw.Pszemek
Nov 26 '18 at 12:12
P.S. Do you think, that does it matter, that Fetch is called by React app?
– Przemyslaw.Pszemek
Nov 26 '18 at 14:35
|
show 1 more comment
Client side says it is sending application/json, But
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
Is not JSON. Looks more like data you would send in a query string.
Construct a valid JSON payload
const data = {
Name: ${this.state.surveyState.name},
Change: ${this.state.surveyState.change},
Opinion: ${this.state.surveyState.opinion}
};
And send it in the correct format to the server
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Finally, let the Server action know to expect the data in the body of the request by using [FromBody]
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey) {
if (survey == null) {
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
I did like you posted, and nothing hits the break points inside ofpublic IActionResult AddComment([FromBody]Survey survey)
– Przemyslaw.Pszemek
Nov 25 '18 at 22:27
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
@Przemyslaw.Pszemek in your update you still appear to be sending the data incorrectly. Review my answer carefully and notice how I construct the data to be sent.
– Nkosi
Nov 26 '18 at 11:07
@I tryed your approach, please see latest UPDATE on the question. Because of some reason, I am getting inXHRlogs old URL:http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good, even after changing Fetch URL to:/Survey/AddComment. I have the same result also with using format:${this.state.surveyState.name}for the properties.
– Przemyslaw.Pszemek
Nov 26 '18 at 12:12
P.S. Do you think, that does it matter, that Fetch is called by React app?
– Przemyslaw.Pszemek
Nov 26 '18 at 14:35
|
show 1 more comment
Client side says it is sending application/json, But
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
Is not JSON. Looks more like data you would send in a query string.
Construct a valid JSON payload
const data = {
Name: ${this.state.surveyState.name},
Change: ${this.state.surveyState.change},
Opinion: ${this.state.surveyState.opinion}
};
And send it in the correct format to the server
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Finally, let the Server action know to expect the data in the body of the request by using [FromBody]
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey) {
if (survey == null) {
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
Client side says it is sending application/json, But
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
Is not JSON. Looks more like data you would send in a query string.
Construct a valid JSON payload
const data = {
Name: ${this.state.surveyState.name},
Change: ${this.state.surveyState.change},
Opinion: ${this.state.surveyState.opinion}
};
And send it in the correct format to the server
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Finally, let the Server action know to expect the data in the body of the request by using [FromBody]
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey) {
if (survey == null) {
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
edited Nov 26 '18 at 10:19
answered Nov 25 '18 at 22:18
NkosiNkosi
117k17133199
117k17133199
I did like you posted, and nothing hits the break points inside ofpublic IActionResult AddComment([FromBody]Survey survey)
– Przemyslaw.Pszemek
Nov 25 '18 at 22:27
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
@Przemyslaw.Pszemek in your update you still appear to be sending the data incorrectly. Review my answer carefully and notice how I construct the data to be sent.
– Nkosi
Nov 26 '18 at 11:07
@I tryed your approach, please see latest UPDATE on the question. Because of some reason, I am getting inXHRlogs old URL:http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good, even after changing Fetch URL to:/Survey/AddComment. I have the same result also with using format:${this.state.surveyState.name}for the properties.
– Przemyslaw.Pszemek
Nov 26 '18 at 12:12
P.S. Do you think, that does it matter, that Fetch is called by React app?
– Przemyslaw.Pszemek
Nov 26 '18 at 14:35
|
show 1 more comment
I did like you posted, and nothing hits the break points inside ofpublic IActionResult AddComment([FromBody]Survey survey)
– Przemyslaw.Pszemek
Nov 25 '18 at 22:27
I tryed it again with fetch call, with same result (please see edited question). What I noticed, inXHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?
– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
@Przemyslaw.Pszemek in your update you still appear to be sending the data incorrectly. Review my answer carefully and notice how I construct the data to be sent.
– Nkosi
Nov 26 '18 at 11:07
@I tryed your approach, please see latest UPDATE on the question. Because of some reason, I am getting inXHRlogs old URL:http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good, even after changing Fetch URL to:/Survey/AddComment. I have the same result also with using format:${this.state.surveyState.name}for the properties.
– Przemyslaw.Pszemek
Nov 26 '18 at 12:12
P.S. Do you think, that does it matter, that Fetch is called by React app?
– Przemyslaw.Pszemek
Nov 26 '18 at 14:35
I did like you posted, and nothing hits the break points inside of
public IActionResult AddComment([FromBody]Survey survey)– Przemyslaw.Pszemek
Nov 25 '18 at 22:27
I did like you posted, and nothing hits the break points inside of
public IActionResult AddComment([FromBody]Survey survey)– Przemyslaw.Pszemek
Nov 25 '18 at 22:27
I tryed it again with fetch call, with same result (please see edited question). What I noticed, in
XHR console logs call type is GET, not POST, also for ajax call. I do not understand why?– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
I tryed it again with fetch call, with same result (please see edited question). What I noticed, in
XHR console logs call type is GET, not POST, also for ajax call. I do not understand why?– Przemyslaw.Pszemek
Nov 26 '18 at 9:59
@Przemyslaw.Pszemek in your update you still appear to be sending the data incorrectly. Review my answer carefully and notice how I construct the data to be sent.
– Nkosi
Nov 26 '18 at 11:07
@Przemyslaw.Pszemek in your update you still appear to be sending the data incorrectly. Review my answer carefully and notice how I construct the data to be sent.
– Nkosi
Nov 26 '18 at 11:07
@I tryed your approach, please see latest UPDATE on the question. Because of some reason, I am getting in
XHR logs old URL: http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good, even after changing Fetch URL to: /Survey/AddComment. I have the same result also with using format: ${this.state.surveyState.name} for the properties.– Przemyslaw.Pszemek
Nov 26 '18 at 12:12
@I tryed your approach, please see latest UPDATE on the question. Because of some reason, I am getting in
XHR logs old URL: http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good, even after changing Fetch URL to: /Survey/AddComment. I have the same result also with using format: ${this.state.surveyState.name} for the properties.– Przemyslaw.Pszemek
Nov 26 '18 at 12:12
P.S. Do you think, that does it matter, that Fetch is called by React app?
– Przemyslaw.Pszemek
Nov 26 '18 at 14:35
P.S. Do you think, that does it matter, that Fetch is called by React app?
– Przemyslaw.Pszemek
Nov 26 '18 at 14:35
|
show 1 more comment
The line
name: "default", template: "{controller}/{action}/{id?}",
means that the path /Survey/AddComment will call the Action
SurveyController.AddComment()
The id marked with "?" is optional ({id?}).
If you want to define the route in the Controller you can do something like the following.
[Route("[controller]/[action]")]
public class SurveyController : Controller {
[HttpPost]
public ActionResult AddComment(Survey survey)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Content("Added");
}
}
In both cases you have to mark the Action with [HttpPost] if you send a POST request.
I did like you proposed, and it does not go throu the action, because of some reason
– Przemyslaw.Pszemek
Nov 25 '18 at 22:11
add a comment |
The line
name: "default", template: "{controller}/{action}/{id?}",
means that the path /Survey/AddComment will call the Action
SurveyController.AddComment()
The id marked with "?" is optional ({id?}).
If you want to define the route in the Controller you can do something like the following.
[Route("[controller]/[action]")]
public class SurveyController : Controller {
[HttpPost]
public ActionResult AddComment(Survey survey)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Content("Added");
}
}
In both cases you have to mark the Action with [HttpPost] if you send a POST request.
I did like you proposed, and it does not go throu the action, because of some reason
– Przemyslaw.Pszemek
Nov 25 '18 at 22:11
add a comment |
The line
name: "default", template: "{controller}/{action}/{id?}",
means that the path /Survey/AddComment will call the Action
SurveyController.AddComment()
The id marked with "?" is optional ({id?}).
If you want to define the route in the Controller you can do something like the following.
[Route("[controller]/[action]")]
public class SurveyController : Controller {
[HttpPost]
public ActionResult AddComment(Survey survey)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Content("Added");
}
}
In both cases you have to mark the Action with [HttpPost] if you send a POST request.
The line
name: "default", template: "{controller}/{action}/{id?}",
means that the path /Survey/AddComment will call the Action
SurveyController.AddComment()
The id marked with "?" is optional ({id?}).
If you want to define the route in the Controller you can do something like the following.
[Route("[controller]/[action]")]
public class SurveyController : Controller {
[HttpPost]
public ActionResult AddComment(Survey survey)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Content("Added");
}
}
In both cases you have to mark the Action with [HttpPost] if you send a POST request.
answered Nov 25 '18 at 22:06
koalabruderkoalabruder
1,44552434
1,44552434
I did like you proposed, and it does not go throu the action, because of some reason
– Przemyslaw.Pszemek
Nov 25 '18 at 22:11
add a comment |
I did like you proposed, and it does not go throu the action, because of some reason
– Przemyslaw.Pszemek
Nov 25 '18 at 22:11
I did like you proposed, and it does not go throu the action, because of some reason
– Przemyslaw.Pszemek
Nov 25 '18 at 22:11
I did like you proposed, and it does not go throu the action, because of some reason
– Przemyslaw.Pszemek
Nov 25 '18 at 22:11
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%2f53471658%2fwhy-my-ajax-fetch-call-does-not-work-with-no-route-in-my-controller%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
It would help if you add the class Attributes, the class name of the controller (SurveyController???], the Attributes of the action AddComment() and perhaps the routing definition of your Startup.cs to the example. Of course if you want to handle a POST you have to use the Attribute HttpPost.
– koalabruder
Nov 25 '18 at 21:33
@koalabruder updated
– Przemyslaw.Pszemek
Nov 25 '18 at 21:37
I tryed it again with fetch call, with same result (please see edited question). What I noticed, in
XHRconsole logs call type isGET, notPOST, also forajaxcall. I do not understand why?– Przemyslaw.Pszemek
Nov 26 '18 at 9:59