How to send success or failure status to AJAX calls from Asp.Net Web API - ajax

I am working on an asp.net C# Web API project. I am posting data from a client using jQuery AJAX. The code is given below. I have tried two types of AJAX calls as shown below. Whether the API succeeds or not, the code under either success or error is never reached in the AJAX.
Asp.Net Web API Code:
[HttpPost]
[Route("SendCustomerDetails")]
public async Task<IHttpActionResult> SendCustomerDetails([FromBody] String jsonData)
{
//Code to process json
//...
//...
resp = await client.PostAsJsonAsync("customer/newcustomer", jObject);
if (resp.IsSuccessStatusCode)
{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
else{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
}
Jquery AJAX code1:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json"
}).done(function (data) {
alert("Success: " + data);
$('#value1').text(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("failure: " + jqXHR.responseText || textStatus);
$('#value1').text(jqXHR.responseText || textStatus);
});
Jquery AJAX code2:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json",
success: function(data) {
alert("Success: " + data);
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});

fix the action
[HttpPost]
[Route("~/SendCustomerDetails")]
public IActionResult SendCustomerDetails(JObject model)
{
return Ok(" It is Success");
}
try this code
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
data: { model:jsonData},
success: function(data) {
alert("Success: " + JSON.stringify(data));
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});

Related

.NET 6 (Core) MVC application - problem with ajax call

.NET 6 (Core) MVC application. In view I have:
$("#mybtn").click(function () {
$.ajax({
type: "POST",
url: "/MyController/GetCustomer",
data: JSON.stringify({ 'id': 5 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response, textStatus, xhr) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
and in controller:
[HttpPost]
public JsonResult GetCustomer(int? id) {
if (id == null) {
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { msg = "Error in the request." });
}
var customer = _db.Customers.Find(id);
return Json(customer);
}
It gets to the action method in controller, but the id is always null...
What am I doing wrong?
It gets to the action method in controller, but the id is always
null... What am I doing wrong?
To begin with, you don't need to use JSON.stringify({ 'id': 5 }) as { 'id': 5 } already in json format. In addition, contentType: "application/json; charset=utf-8", is uncessary as well, Instead, you can do as following:
Correct Format:
$("#mybtn").click(function () {
$.ajax({
url: "/MyController/GetCustomer",
type: "POST",
data: { 'id': 5 },
dataType: "json",
success: function (response, textStatus, xhr) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
Note: You are getting null in your controller because of using contentType: "application/json; charset=utf-8", and additional, Json parsing here JSON.stringify() these are only valid when you are sending parameter as object fashion. Just get rid of those two part, you are done.
Output:

ASP.NET MVC AJAX POST ValidateAntiForgeryToken

With my code i get a internal Server error:
#using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
#Html.AntiForgeryToken()
}
<script>
function Like(id) {
var requestData = {
profileId: id,
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
};
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: JSON.stringify(requestData),
dataType: "json",
contentType: 'application/json; charset=utf-8',
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }
If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?
I see in fiddler SyntaxView 2 requests:
/Manage/Like
{"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}
/Manage
__RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2
Taking this from a sim. question here include antiforgerytoken in ajax post ASP.NET MVC
function Like(id) {
var form = $('form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: { __RequestVerificationToken: token, profileID: id },
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}

AJAX Internal server error

I couldnt find out what is the error.
<script type="text/javascript">
$(document).ready(function () {
$("#btnsumbit").click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: '{"username":"' + $("input#txtuser").val() + '","password":"' + $("input#txtpwd").val() + '"}',
url: 'http://localhost:53179/hdfcmobile/WebService.asmx/Login_Data',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
var status = data.Status;
alert(data.d);
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
});
</script>
I am getting 500 internal server error.How to call this webservice.I have passes the method with the url.Thanks for any help...
First thing, the way you are sending is wrong, send it like this
data: {
"username": $("input#txtuser").val(),
"password": $("input#txtpwd").val()
}
Next make sure, url: http://localhost:53179/hdfcmobile/WebService.asmx/Login_Data is returning JSON output.

ajax jquery pass null value

I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});

Ajax Json multiple parameters

This code below sitting on a ASP.Net application on the Site.Mater....
I need to pass another two parameters from the default.aspx page, one asp:label and one asp:textbox
What is the easiest way to do that?
Thanks
<script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "TestWebService.asmx/FetchList",
data: "{ 'testName': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
In your jQuery autocomplete, You need to change your data parameter to this:
data: "{ 'testName': '" + request.term + "' ,lbl: '" + $(".lblClass").text() + "' ,txt: '" + $(".txtClass").val() + "'}"
And then change your service method like this:
[WebMethod]
public List<string> FetchList(string testName, string lbl, string txt)
{
//...
}
Note:
.lblClass and .txtClass are classes for ASP:Lable and ASP:TextBox respectively.

Resources