Passing parameter to MVC Action via Ajax always null - ajax

I looked at related questions to to form my ajax request but I can't figure out why this isn't working as the param is always null in the acion
I've done a console.log to check that item in 'data: { data: item }' has a value
//action
public async Task<IActionResult> DeleteMedia(string data)
{
$("#mediaTable").on('click', 'td:nth-child(7)', function () {
var item = $(this).parent().attr("id");
$("#MediaToDownload").val(item);
$.ajax({
url: '#Url.Action("DeleteMedia", "Home")',
type: 'get',
cache: false,
processData: false,
contentType: false,
data: { data: item },
success: function (data) {
location.href = data;
}
});
});

You need to send just the string, as JSON:
data: JSON.stringify(item)

Related

$.ajax data is null

I need to save the record in the database. I have been doing this thing but I don't know for what reason it is giving me this error. Any help will be appreciated. I don't know why the data is null. Please refer to the error show in below screenshot:
data is not defined
function submit(amount) {
var _url = ' /Home/SaveDepositedAmount';
console.log(_url);
$.ajax({
type: "POST",
async: false,
cache: false,
beforeSend: function () { ShowLoading(); },
url: _url,
processData: false,
contentType: false,
dataType: 'json',
data: { amount: amount },
})
.done(function (data) {
Server side code is:
[HttpPost]
public JsonResult SaveDepositedAmount(int amount)
{
JsonResult result = new JsonResult();
int userId = Authentication.Instance.User.UserId;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
You’re passing an object through to the server side but it’s only expecting an int.
Create an object with 1 property (int Amount) and use that instead of the int for your server side parameter

Controller values getting null object for the update request from the ajax call in mvc

When the ajax requests the controller to update the entity , I can see the list values in the ajax . But when it hits the controller , the same object is getting null.
$.ajax({
traditional: true,
async: true,
type: 'PUT',
headers: { 'X-CSRF-TOKEN': $("input[name='__RequestVerificationToken']").val() },
url: "/AccessLevel/ModifyAccessLevelFeatureMapping",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(accessLevelFeatureList),
processData: false,
cache: false,
success: function (data)
{
}
controller>>
[HttpPut]
[ExcludeFromCodeCoverage]
public async Task<JsonResult> ModifyAccessLevelFeatureMapping([FromBody]IEnumerable<FeatureMasterModel> featureModel) --null value!!
{
try
{
var accessLevelFeatures = await accessLevelService.UpdateAccessLevelFeature(featureModel);
return Json(new { accessLevelFeatures });
}
}

ASP.NET & Ajax - How to pass value from ajax to action?

I have a few checkboxes on my page. I have some jquery in place to ensure that only one checkbox is checked at a time. I have assigned a specific value to each checkbox. The below ajax finds the checkbox that is checked and I'm grabbing the value associated to it. How do I pass that value to my action?
AJAX
$("input:checkbox").click(function () {
var PaymentID = document.querySelector('#chkBox:checked').value;
alert(PaymentID); // for test
$.ajax({
type: "POST",
dataType: "json",
data: PaymentID,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("MyAction", "Home")",
success: function () {
return PaymentID; // Failed attempt at passing data.
}
})
})
Action:
[HttpPost]
public ActionResult MyAction(string PaymentID)
{
// Magic
}
Please keep in mind i am fairly new to ajax. Thx guys.
You can pass a javascript object with name PaymentID ( same name as your action method parameter)
data: { PaymentID: PaymentID },
You do not need to specify contentType as you are sending a simply object. Also you do not necessarily need to specify dataType for your ajax call to send the data.
This should work.
var PaymentID = "some value";
$.ajax({
type: "POST",
data: { PaymentID: PaymentID },
url: "#Url.Action("MyAction", "Home")",
success: function (response) {
console.log('response', response);
}
});
Or you can use the $.post method.
$.post("#Url.Action("MyAction", "Home")",{ PaymentID: PaymentID }, function(response) {
console.log('response', response);
});

Go to new view on AJAX success using ActionResult

I have an AJAX call that posts data to the server to save to the DB. When this is complete, I want to call another ActionResult in the success callback to switch the user to a brand new view. This needs no data passed to it, I just need the success in the Ajax to call this method. Is this possible? I played with some of the URL helpers but I can seem to make this work, it just does nothing.
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === true) {
alert('Yes');
} else {
alert('No');
}
},
failure: function() {
alert('No');
}
So this would be in the first part of the success callback where it is currently set at aler('Yes').
Do something like this:
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === 'true') {
window.location.href = 'Success/';
} else {
//handle the failure from the response
}
},
failure: function() {
//handle the failure of the request itself
}

Ajax post parameters ASP.NET MVC 3

Hello guys i have the next ajax call for login. I serialize the form and send the data to server and return redirect url link. My problem is that my url after post is like
http://localhost:50802/?username=&password= and not http://localhost:50802/Home
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
alert(result.link);
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
It looks like you wrote this $.ajax call in the .click event of a submit button or in the .submit event of a form without canceling the default action by returning false from the callback or by calling preventDefault on the argument. Here's how your code should look like:
$('#id_of_your_form').submit(function(e) {
e.preventdefault(); // <-- That's what I am talking about and what you forgot
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
});
Also async: false,????? You know what this does, do you? That's not AJAX. That's a blocking synchronous call to your webserver during which the client browser would be frozen like during the Ice Age 2 ruining all user experience.
Try returning false at the end of your submit function
$('#id_of_your_form').submit(function(e) {
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
return false; });
Another option would of course be to return the correct redirectlink from the controller instead of overriding it in the java script.

Resources