Ajax post can't find action controller - ajax

I'm writing a simple web app that allows users to login via facebook. When using the javascript sdk, I'm able to retrieve the proper credentials, but my ajax post is unable to find the mvc action to process the information.
Here's the js code:
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
var credentials = { uid: response.authResponse.userID, accessToken: response.authResponse.accessToken };
SubmitLogin(credentials);
}
});
function SubmitLogin(credentials) {
alert("Creds: " + credentials.uid + ":::" + credentials.accessToken);
$.ajax({
type: "POST",
ContentType: 'application/json',
url: '#Url.Action("FacebookLogin","Home")',
data:JSON.stringify(credentials),
success: function () {
window.location("~/Views/Account/Home.cshtml");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
}
and the corresponding controller:
[HttpPost]
public JsonResult FacebookLogin(string uid, string accessToken)
{
Session["uid"] = uid;
Session["accessToken"] = accessToken;
return null;
}
The model used in the controller:
public class FBLoginModel
{
public string uid { get; set; }
public string accessToken { get; set; }
}
The alert in the js function shows the correct token, but my ajax post is unable to the action. When I remove the "[HttpPost]" above the controller, I can access the action, but all data I attempt to pass is null.
Any help would be greatly appreciated. Thanks.

use
$.ajax({
type: "POST",
ContentType: 'application/json',
url: '#Url.Action("FacebookLogin","Home")',
data:JSON.stringify(credentials),
success: function () {
window.location("~/Views/Account/Home.cshtml");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
Ther should be single quote in 'Url.Action()'
Yout Controller action should be like below.Because you are not passing model items
public JsonResult FacebookLogin(long uid,string accessToken)
{
Session["uid"] = uid;
Session["accessToken"] = accessToken;
return null; //Because you are not posting anything back
}

I somehow devised a solution... By writing out the url and adding a forward slash to my ajax call, somehow my ajax call can find my action.
$.ajax({
type: 'POST',
url: 'Home/FacebookLogin/',
data: {
'uid': response.authResponse.userID,
'accessToken': response.authResponse.accessToken
},
cache: false,
success: function (result) { },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});

Related

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

MVC Controller post json does not work

I have the this code to post json to a controller.
The problem is that the credentials object does not get populated with the posted values.
How do I change this code so that it works?
I see in Fiddler that the request is being posted correctly.
[HttpPost]
public JsonResult Authenticate(CredentialsModel credentials)
{
return Json(credentials);
}
[DataContract]
public class CredentialsModel
{
[DataMember(Name = "user")]
public string User;
[DataMember(Name = "pass")]
public string Pass;
}
$.ajax({
type: "POST",
url: "/login/authenticate",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{"user":' + JSON.stringify($('#username').val()) + ',"uass":' + JSON.stringify($('#userpass').val()) + '}',
dataType: "json",
timeout: 100,
success: function (msg) {
},
complete: function (jqXHR, status) {
if (status == 'success' || status == 'notmodified') {
var obj = jQuery.parseJSON(jqXHR.responseText);
}
},
error: function (req, status, error) {
}
});
The default MVC model binder only works with properties. Your CredentialsModel is using fields. Try changing them to properties. You can also remove the annotations.
public class CredentialsModel
{
public string User { get; set; }
public string Pass { get; set; }
}
Also, as pointed out by Sahib, you can create a Javascript Object and then stringify it, rather than stringifying each one. Although that doesn't appear to be the problem in this case.
data: JSON.stringify({
User: $('#username').val(),
Pass: $('#userpass').val()
})
Try chaning your data like this :
$.ajax({
.................
//notice the 'U' and 'P'. I have changed those to exactly match with your model field.
data: JSON.stringify({User: $('#username').val(),Pass: $('#userpass').val()}),
.................
});

WebApi passed data is null

Controller code:
[HttpPost]
public void UpdateClient(Client client)
{
// Rest of code
}
Client code:
$.ajax({
url: "api/client/UpdateClient",
type: 'post',
contentType: 'application/json',
data: "{client: " + ko.toJSON(model.selectedClient()) + "}",
success: function (result) {
getClients();
$("#loader").hide();
},
failure: function (result) {
alert(result.d);
$("#loader").hide();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("An error occurred, please try again.");
$("#loader").hide();
}
});
For whatever reason the parameter 'client' is always null despite checking that model.selectedClient() is ok and the ko.toJSON is working.
I don't think you need to adding the 'client' padding to your data. Try setting data to:
ko.toJSON(model.selectedClient())
The 'client' parameter got model bound correctly for me when my Client class looks like this:
public class Client
{
public string Name { get; set; }
public string Company { get; set; }
}
... and my ajax looks like this:
$.ajax({
url: "api/values/UpdateClient",
type: "post",
contentType: 'application/json',
data: "{ 'Name': 'John', 'Company': 'ABC'}"
});

MVC3 jquery ajax parameter data is null at controller

I have a controller action that I want to update via a jquery call. The action runs, but there is no data in the parameters.
I am using a kedoui grid with a custom command in a column that I want to run some server code.
kendoui grid in view
...
columns.Command(command =>
{
command.Custom("ToggleRole").Click("toggleRole");
});
...
The model is of type List<_AdministrationUsers>.
public class _AdministrationUsers
{
[Key]
[ScaffoldColumn(false)]
public Guid UserID { get; set; }
public string UserName { get; set; }
public string Role { get; set; }
}
Here is my toggleRole Script:
<script type="text/javascript">
function toggleRole(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
alert(JSON.stringify(dataItem));
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
}
</script>
Here is my controller action:
[HttpPost]
public ActionResult ToggleRole(string UserID, string UserName, string Role)
{
...
}
The controller action fires, but there is no data in any of the parameters.
I put the alert in the javascript to verify that there is indeed data in the "dataItem" variable. Here is what the alert text looks like:
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Did you try specifying the dataType and contentType in you ajax post ?
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
It looks like you are posting the whole object as one Json string, while the controller expects three strings. If you are using MVC3 the parameter names also have to match the controllers signature. Try to parse up your data object so that it matches the input expected from the controller. Something like this:
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: { UserID: dataItem.UserID, UserName: dataItem.UserID, Role: dataItem.Role },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
Hope that helps!
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Seems incorrect to me. Wouldn't you want this?
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role" : "Admin"}
Notice the "Role" : "Admin"

ajax call results in error instead of succes

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?
I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow
Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });
Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Resources