WebApi passed data is null - asp.net-web-api

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'}"
});

Related

Post ajax data to MVC controller

I have the following ajax in a .chtml file:
var planID = $("#PlanID").val();
if (planID.length == 4) {
$(ctl).prop("disabled", true).text(msg);
$("#nextButton").prop("disabled", true);
setTimeout(function () {
$(".submit-progress").removeClass("hidden");
}, 1);
$.ajax({
type: "POST",
url: "/ForgotUserID/CheckPlanID",
data: '{planID: "' + planID + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("ajax success function");
$("form").submit();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
//$("form").submit()
}
And I have the following in my ForgotUserIDController:
[HttpPost]
public JsonResult CheckPlanID(string planID)
{
ForgotUserID forgotUserID = new ForgotUserID()
{
PlanID = planID
};
return Json(forgotUserID);
}
When I run the code, I see this in the dev tools under network:
So I know the data that I typed into my input box is floating around somewhere.
When I have a breakpoint set in my controller, the value of planID is null. Shouldn't the value get passed from the ajax data component?
How can I get the data typed into the input box passed to my controller?
Any assistance is greatly appreciated.
Thank you!
if you want to use contentType: "application/json; charset=utf-8",
fix ajax data line
data: JSON.stringify({ planID : planID }),
and create viewmodel and use frombody attribute in action
public JsonResult CheckPlanID([FromBody] PlanViewModel model)
{
string planID=model.PlanID;
....
}
public class PlanViewModel
{
public string PlanID {get;set;}
}
or remove contentType: "application/json; charset=utf-8" and fix data
//contentType: "application/json; charset=utf-8",
data: { planID : planID },
in this case you don't need and extra class and frombody attribute. Leave your action header as it is

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()}),
.................
});

Ajax post can't find action controller

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);
}
});

controller is not geting view data

function export(){
$.ajax({ url: "#Url.Content("~/controllr/method")",
type: 'GET',
data: { selectedValue : $("#BranchId option:selected").text() },
traditional: true,
async:false,
success: function (result ) {
},
failure: function () {
failed=true;
alert("Error occured while processing your request");
},
error: function (xhr, status, err) {
failed=true;
alert("Error occured while processing your request");
}}
Did you try setting a breakpoint on the controller action and see whether its is being hit ? Please try the following basic code and see whether the call is getting through
$.ajax({
url: ‘#Url.Content(“~/MyController/MyMethod”)’,
type: ‘post’,
data: {
selectedBranchId : $("#BranchId option:selected").text()
}
});
// I am the controller action
public ActionResult MyMethod(string selectedBranchId)
{
// your code
}
Please note I have dropped all the callback code and changed the controller name and the action name with the name of the postback variable

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"

Resources