I have a webapi method defined like the following in a controller:
[Authorize]
[HttpPost]
[Route("api/Resources/{resourceID:int}/VerifyUrl")] //Custom Routing
public object VerifyResourceURL([FromBody]string url, int resourceID)
When I call it with jquery ajax the variable url is always null, why?
(resourceID has the correct value)
$.ajax({
url: '/api/resources/15/VerifyUrl',
type: "POST",
async: true,
dataType: "json",
data: { url: 'some-url-to-verify' },
success: function (data) {
if (data.Exist === false) {
urlIsValid = true;
}
else {
alert('URL already exist');
urlIsValid = false;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus, "Error: " + errorThrown);
}
});
You're sending an object with a url property, but expecting the body to be a string.
Try changing datatype and data as such:
dataType: "text",
data: 'some-url-to-verify',
I have sample code and you can try something like this
//JavaScript
var command = {
url: $("#txtOrigin").val()
};
$.ajax({
type: "POST",
url: "/api/booking",
contentType: "application/json",
data: JSON.stringify(command),
dataType: "text",
success: Created,
error: Failed
});
//C# MVC Controller
public async Task<IActionResult> Create([FromBody] CreateBookingCommand command)
{
}
Related
My c# action looks like:
[HttpPost]
public JsonResult GetItems(int id)
{
var productsQryList = some-query-to-getitems.ToList();
if(productsQryList != null)
{
return Json(productsQryList);
} else
{
return Json(new());
}
}
In my view, the autocomplete configuration looks like:
$("#productInfo").autocomplete({
minLength: 1,
source: function( request, response ) {
$.ajax({
type: "GET",
url: "/api/purchase/SearchProductsSimple",
data: {
term: request.term
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function( data ) {
response( data );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function (event, ui) {
if (ui.item) {
$("#order-items-table tbody tr").remove();
$.ajax({
cache: false,
type: "POST",
url: "/api/purchase/GetItems",
data: { "id": ui.item.value },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (itemList) {
for(const item of itemList) {
appendOneRow(item);
counter++;
}
countTrSetIndex();
return false;
}))
},
failure: function (response) {
alert(response.d);
}
});
}
}
});
In firefox plugin RESTED,
The GetItems method runs good if I change its attribute to HttpGet.
But, if The attribute is HttpPost, I got 400 error.
By the way, The select event must be POST call.
wait for resolution.
Thank you guys.
You might have [AutoValidateAntiforgeryToken] attribute on your controller, so you must send forgery token value at ajax call.
data: { "id": ui.item.value,
"__RequestVerificationToken":$( "input[name='__RequestVerificationToken']" ).val() },
This question already has answers here:
How do you post a JSON file to an ASP.NET MVC Action?
(4 answers)
Closed 3 years ago.
I am trying to send my email and password to my home Controller jsonresult method.
values of email and password are displayed in first alert but when i am passing userCredential to data it displays alert undefined.
values of email and password are not getting passed in ajax post method
$("#button_val").click(function () {
var userCrdential = "email=" + $("#username").val() + "&password="
+ $("#pwd").val();
alert(userCrdential);
$.ajax({
type: "POST",
url: "/Home/adduser",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: userCrdential,
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});.
controller
[HttpGet] public JsonResult adduser(user obj) { }
By looking at your comment, the first thing that I observed is that, you are using the post method on ajax call while at the controller level, it is the http get. It could be the problem. It is good if you can put the code for your action method too.
Here is the sample example of post object through ajax in mvc,
[HttpPost]
public ActionResult YourMethodName(MyViewModel myViewModel)
{
//your code goes here.
}
You can make the ajax call like below,
var requestData = {
Email: 'pass the email value here',
Password: 'pass the password value here')
};
$.ajax({
url: '/en/myController/YourMethodName',
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
});
In your controller method you use [HttpGet] but in ajax request you write POST. So, go to one option POST or GET. I write the solution with GET First change your Controller method with this:
[HttpPost]
public JsonResult adduser(string email, string password) {
// work here
}
Then modify your code:
$("#button_val").click(function () {
var userCrdential = "email:"+ $("#username").val()+", password:"+ $("#pwd").val();
alert(userCrdential);
$.ajax({
type: "POST",
url: "/Home/adduser",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {userCrdential },
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});
I want to get new value from controller and set it to view when form submit.
Controller:
public JsonResult GetVoucherNo()
{
var voucherno = 1001;
var lastvoucherno = db.PaymentsAndReceipts.Where(x => x.StakeHolder.StakeHolderType.Name == "Supplier").OrderBy(x => x.VoucherNo).ToList().LastOrDefault();
if (lastvoucherno != null)
{
voucherno = lastvoucherno.VoucherNo.GetValueOrDefault() + 1;
}
return new JsonResult { Data = voucherno, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My Jquery function:
I just want to do when this function calls, I can get the value from controller action.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function () {
//don't know what to do here.
});
}
The data should be available in the done function argument like this:
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function (result) {
//don't know what to do here.
console.log(result);
//you should see the exact JSON you return from the controller
});
}
I done it with success.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '/Payments/GetVoucherNo',
dataType: "json",
success: function (result) {
console.log(result);
return $('#VoucherNo').val(result); //to set value in textbox.
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr, status, error);
}
});
}
Java Script:-
function themechange(themeValue) {
$('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
In LoginContoller.cs:-
[HttpGet]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
All the suggestion which replied so far are not working. Please give a executable project codes links for ASP.NET MVC Application which applies simple ajax with json for just calling a controller method.
You forget to assign the themeValue which get from HTML page by $('#themeId') also there is a problem you use GET instead of POST.
Try this
function themechange(themeValue) {
var themeValue = $('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
[HttpPost]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
I'm currently working on an ASP.Net MVC project.
I have a JavaScript function which takes an XML string as input. I would like to send this to the controller.
I have done so using an AJAX request, but in the controller the string is null.
View:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")'
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: xml,
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public ActionResult Save(string xml)
{
Console.WriteLine(xml);
W6ViewModel viewModel = new W6ViewModel();
viewModel.engineers = db.W6ENGINEERS.ToList();
viewModel.tasks = db.W6TASKS.ToList();
viewModel.skills = db.W6TASKS_REQUIRED_SKILLS1.ToList();
var engList = new List<object>();
foreach (var engineer in viewModel.engineers)
{
engList.Add(new { key = engineer.ID, label = engineer.Name });
}
ViewBag.engineers = engList;
return View("Index", viewModel);
}
var xml = scheduler.toXML()
alert(xml):
Error Code (Sorry, wall of text):
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client (xmlString="<data><event>
Name your parameter like this:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")';
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: { xml: xml},
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Also put this tag above you controller action:
[ValidateInput(false)]
See the following ajax call:
$.ajax({
url: '#Url.Content("~/myaccount/CheckDuplicateEmailAddress")',
data: { "emailAddress": email },
async: false,
type: "post",
success: success,
error: error
});
And controller action is below. you need to send param as this:
data: { "emailAddress": email }
Remember case sensitivity and double quotes:
public bool CheckDuplicateEmailAddress(string emailAddress)
{
}