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

.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:

Related

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

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));
}
});

How to invoke another function using a parameter fetched JSON result of API call from AJAX

I Have to get ParentId from this function using JSON result and then invoke another function given below after this function:
public fetchLibraryDatafromSharePointList(clientID:string) {
debugger;
const reactHandler = this;
jquery.ajax({
url: `${this.props.siteurl}/_api/web/lists/getbytitle('MSAs')/items?$filter=ClientID eq '${clientID}'&$orderby=Modified desc`,
type: "GET",
headers:{'Accept': 'application/json; odata=verbose;'},
success: function(resultData2) {
reactHandler.setState({
items: resultData2.d.results
});
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
Below is the function which has to be invoked on the success of above API and the parameter is coming in the JSON result of the previous call made:-
SetState is done by reactHandler variable
public fetchDatafromSharePointList(ParentID) {
debugger;
const reactHandler = this;
jquery.ajax({
url:`${this.props.siteurl}/_api/web/lists/getbytitle('MSASummaries')/items?
$filter=Parent eq ${ParentID}$top=1&$orderby=Modified desc`,
type: "GET",
headers:{'Accept': 'application/json; odata=verbose;'},
success: function(resultData) {
/*resultData.d.results;*/
reactHandler.setState({
items: resultData.d.results
});
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
You can invoke another function in the success response of fetchLibraryDatafromSharePointList(clientID:string) after updating state. i.e:
reactHandler.setState({
items: resultData2.d.results
}, ()=>{
fetchDatafromSharePointList(your_parent_id_goes_here);
});

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
});
}

VaryByParam not working with parameter, only *

I've taken a look at the other VaryByParam questions, but I haven't been able to find the answer to my question. I have an MVC site that has the following action defined:
[OutputCache(Duration = 30, VaryByParam = "TargetID")]
public JsonResult IsThingAllowed(int TargetID)
{
bool isAllowed = IsAllowed(TargetID);
return Json(isAllowed, JsonRequestBehavior.AllowGet);
}
No matter what comes in for TargetID, the cached value gets returned. However, if I change TargetID to be *, it works as expected (cached values vary by TargetID):
[OutputCache(Duration = 30, VaryByParam = "*")]
Here's the AJAX call:
$.ajax({
url: "/MyController/IsThingAllowed",
type: "POST",
data: JSON.stringify({ "TargetID": id }), // This is definitely varying!
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, xhr) {
updateThing(data);
},
error: function (xhr, textStatus, error) {
}
});
What am I doing wrong when the parameter is explicitly named?
EDIT: Works if we use GET instead of POST.. but POST obviously works, since it works when we use *.
Here's it working with GET:
$.ajax({
url: "/MyController/IsThingAllowed",
type: "GET",
data: { TargetID: id },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, xhr) {
updateThing(data);
},
error: function (xhr, textStatus, error) {
}
});

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.

Resources