I am trying to pass two values to the following controller action using jQuery
[HttpPost]
public JsonResult Cancel(Guid Id, string cancelReason)
{
//do something
}
.js:
CancelProgram = function (Id) {
//this is basically the value from a select tag placed on the form
var reason = $("#CancelReasons").val();
alert(reason);
Origin.ajax({
url: '/ZYX/Cancel?Id=' + Id,
type: 'POST',
dataType: 'json',
data: { cancelReason: reason },
success: function (data) {
alert('success!');
}
});
};
});
The value of cancelReason in the action method is always null. Any pointers on why this is not working?
There must be something wrong with another part of your code. I would start by sending a normal AJAX request by hardcoding the values and ensuring that they are properly sent:
Once you ensure that this simple example works start making it more dynamic by using variables. This way you will be able to narrow down and find the origin of your problem. Also I would very strongly recommend you using a javascript debugging tool such as FireBug. It allows you to see in the Console whether you have javascript errors as well as many other useful information such as the exact requests/responses being sent.
In the case of a successful AJAX request here’s what you should see in the Network Tab of FireBug:
Notice how both the
idand thecancelReasonparameters are sent usingapplication/x-www-form-urlencoded.You should really learn to debug those kind of problems and the way to debug them is by using the proper tools.