ajax call to C# method not working - asp.net-mvc

I want to call a method in C# from a client side AJAX/JQuery message.
The client code is:
function TestClickFunc(userId) {
$.ajax({
url: "/Users/UpdateEmailDistributionListFlag",
type: "POST",
data: { "userId" : userId },
success: function (data) { alert(data); }
});
}
This method gets called with the correct parameter.
However in my UsersController, this method does not get called;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateEmailDistributionListFlag(int userId)
{
// db update
return View();
}
Can you see why?

Check if you have a route with parameter userId. In the default route the parameter's name is id, not userId so your method will not be found.

What I found was that the CDN was not working;
I can't see the spelling mistake, but it worked when I used my local script!

Related

Errors when passing data via jquery ajax

I have a pretty simple ajax request that I'm sending over to server in order to get some data and fill up my edit modal. But for some reason it keeps returning with error and I can't figure out why. I've debugged the server side, parameter comes in correctly and all data is properly found and returned, still an error though.
Here's my code so someone might see what am I missing here.
Request:
function EditNorm(id) {
$.ajax({
type: "POST",
url: "#Url.Action("GetNormViewModel")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({id : id}),
cache: false,
success: function(data) {
FillFormForEditing(data.nvm);
},
error: function() {
alert("Error On EditNorm function");
}
});
}
Server side:
public JsonResult GetNormViewModel(int id)
{
var nvm = new NormViewModel {Norm = db.Norms.Find(id), Materials = db.Materials.ToList()};
return Json(new {nvm = nvm}, JsonRequestBehavior.AllowGet);
}
Firstly: You are using a POST method on your javascript while your controller accepts a Get, add this to your action:
[HttpPost]
public JsonResult GetNormViewModel(int id)
{
return Json(new { ... });
}
Secondly: What is db is it LinqToSQL / Entity Framework context? If so, make sure no call to your data context is performed after the data is returned. (i.e. changed your action and simply return return Json(new { nvm = "test" }); and console.log/alert to make sure you've got the result back. This will tells you that its your model that failed when it's returned due to some late binding.

how to pass data from View to Controller using ajax get or post in mvc with parameters

I am trying to pass data from View to Controller Action Method using ajax as follows:-
I have Membership instance of user which I passed in from another controller to this view below using viewbag somewhat like this ViewBag.MyUser = MyUser;
Now I want to pass 'MyUser' to another Controller form this view using ajax as below.
$('#Link').click(function () {
$.ajax({
url: http://localhost/Account/Process,
type: 'POST',
data: '#ViewBag.MyUser',
success: function () {
},
error: function () {
}
});
The ActionMethod to which I am posting is as follows
public ActionResult Process(MembershipUser MyUser)
{
//Do somethihng with MyUser
}
If I pass do ajax post, I get error internally at BeginExecuteCore(AsyncCallback callback, object state) stating that 'No parameterless constructor defined for this object.' and control does not even comes to my actionmethod.
If I remove the parameter (MembershipUser MyUser) from Action Method it posts to Action method, but then
how can i pass 'MyUser' in such case without parameter from that view to controller ?
is there something wrong with routes ? if yes what should be the route ?
or should i use get or post ?
Where should i cast the MyUser back to MembershipUser ?
The problem is you can't pass MyUser as parameter from JQuery because JQuery doesn't know the class MembershipUser. Remember that JQuery is a client side language and MembershipUser is defined in C# on the server side.
You could pass the properties that you need from the MyUser object to the Process action using GET as follows (supossing that the MyUser object has and ID an a Name):
$('#Link').click(function () {
$.ajax({
url: http://localhost/Account/Process,
type: 'GET',
data: {
id: "#ViewBag.MyUser.ID",
name: "#ViewBag.MyUser.Name"
},
success: function () {
},
error: function () {
}
});
The action should be something like this:
public ActionResult Process(int id, string name)
{
//Do something
}
I hope it helps you!

$.post() not working if the mvc model view controller has a parameter

I´m new with MVC. I´m using MVC4.
I'm having an issue with a callback. If I alert before and after the post() call both alerts show but the call doesn't fire.
[HttpGet]
[Authorize]
public ActionResult Dashboard(int Menu)
{
//some code
return View("Dashboard");
}
<script>
$(document).ready(function () {
$.post("../Client/GetFact", {},
function (data) {
//some code
});
});
</script>
[HttpPost]
[Authorize]
public JsonResult GetFact()
{
//some code to fill object_data
var data = object_data;
return Json(data);
}
As long as I leave ActionResult Dashboard without a parameter is works. If I add a parameter to Dashboard(int Menu) then the call back to GetFact doesn't work.
I searched and found a similar post and follow the instructions given by you guys, but still does not work( looked at: getJSON not working if the mvc model view controller has a parameter).
I do not know what I'm doing wrong. Can you help? Thank's!
I do something similar with $.get, using jquery with the #Url.Action instead of the url.
in addition to using the FormContext to pass to my Action :
Place just before #using (Html.BeginForm())
#{ ViewContext.FormContext = new FormContext(); }
example :
$.get('#Url.Action("ActionName", "ControllerName")', { IDName: $('#IdName').val() }, function (data) {
//Do Something here with the data
});
I would imagine form post would be
$.post('#Url.Ation("ActionName", "ControllerName")', function (data) {
//Do Something here with the data
});
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ type: "POST",
url: url,
data: data,
success: success,// -> call alert here
dataType: dataType});

Why does POST without parameters not return JSON

I have a controller method
[HttpPost]
public ActionResult GetUserData()
{
return Json(GetCurrentUser());
}
I'm calling it $.ajax() through a method like this:
ServerCall: function (method, args, callback) {
$.ajax({
type: 'POST',
url: method,
data: JSON.stringify(args),
contentType: 'application/json;charset=utf8',
dataType: 'json',
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (err) {
}
});
}
with the call being:
ServerCall('GetUserData', null, function(data){
});
As it is, when I make this call, $.ajax returns with success, but 'data' is null. Debugging, responseText is empty. On the server side, GetUserData is called, and it is returning a properly formatted Json object (I've gone so far as to create my own JSON ActionResult and verified that data is indeed being written to the response stream.
If I add a dummy parameter to the server side method:
[HttpPost]
public ActionResult GetUserData(string temp)
{
return Json(GetCurrentUser));
}
everything works perfectly. Browser is IE8. My question is, can anyone explain why this is happening?
UPDATE:
Note workaround solution below: I'd still be interested in knowing the root cause.
No repro.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetUserData()
{
return Json(new { foo = "bar" });
}
}
Index.cshtml view:
<script type="text/javascript">
var serverCall = function (method, args, callback) {
$.ajax({
type: 'POST',
url: method,
data: JSON.stringify(args),
contentType: 'application/json;charset=utf8',
dataType: 'json',
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (err) {
}
});
};
serverCall('#Url.Action("GetUserData")', null, function (data) {
alert(data.foo);
});
</script>
result: 'bar' is alerted (as expected).
I was able to reproduce using Darin's code in IE8. While I don't know the root cause, I think it has something to do with how IE8 JSON.stringify handles null. Changing
data: JSON.stringify(args)
to
data: args ? JSON.stringify(args) : null
fixed the problem.
Note, the problem is intermittent - I was seeing failures in about one out of every ten calls. With the change, over 100 tests, the failure rate was zero.

MVC ajax json post to controller action method

I am trying to achieve a JQuery AJAX call to a controller action method that contains a complex object as a parameter.
I have read plenty blogs and tried several techniques learned from these. The key post on which I have constructed my best attempt code (below) is the stackoverflow post here .
I want to trigger an asynchronous post, invoked when the user tabs off a field [not a Form save post – as demonstrated in other examples I have found].
My intention is to:
Instantiate an object on the client [not the ViewModel which provides the type for the View];
Populate the object with data from several fields in the view;
Convert this object to JSON;
Call the controller action method using the jQuery.Ajax method, passing the JSON object.
The results will be returned as a JSON result; and data will be loaded into fields in the view depending on results returned.
The problems are:
If the action method is attributed with the HttpPost attribute, the controller Action method is not invoked (even though the AJAX call type is set to ‘POST’).
If the action method isattributed with HttpGet, the values of properties of the parameter are null
The ReadObject method throws the error: "Expecting element 'root' from namespace ''.. Encountered 'None' with name 'namespace'".
Hopefully someone can help. Thanks. Code below:
Client js file
var disputeKeyDataObj = {
"InvoiceNumber": "" + $.trim(this.value) + "",
"CustomerNumber": "" + $.trim($('#CustomerNumber').val()) + ""
};
var disputeKeyDataJSON = JSON.stringify(disputeHeadlineData);
$.ajax({
url: "/cnr/GetDataForInvoiceNumber",
type: "POST",
data: disputeKeyDataJSON,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: EnrichedDisputeKeyData(result)
});
Action Filter and class for the type associated with the Action method parameter
[DataContract]
public class DisputeKeyData
{
[DataMember(Name = "InvoiceNumber")]
public string InvoiceNumber { get; set; }
[DataMember(Name = "CustomerNumber")]
public string CustomerNumber { get; set; }
}
Action method on the controller
//[HttpPost]
[ObjectFilter(Param = "disputeKeyData", RootType = typeof(DisputeKeyData))]
public ActionResult GetDataForInvoiceNumber(DisputeKeyData disputeKeyData)
{
//Blah!
//....
return Json(disputeKeyData, JsonRequestBehavior.AllowGet);
}
Below is how I got this working.
The Key point was:
I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});

Resources