Passing json to mvc controller - c#

I am trying to post some data via jQuery ajax to an Asp.Net MVC controller. I have the follow class which I am working with:
public class InnerStyle
{
[JsonProperty("color")]
public string HeaderColor { get; set; }
[JsonProperty("font-size")]
public string HeaderFontSize { get; set; }
[JsonProperty("font-family")]
public string HeaderFontFamily { get; set; }
}
The post method looks like:
public JsonResult UpdateRecord(InnerStyle innerStyle)
{
//Do some validation
return Json("OK");
}
And my jQuery looks like:
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj["font-size"] = value;
console.log(JSON.stringify({ innerStyle: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({ innerStyle: headerObj}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
The console.log in the above change event produces the following JSON string:
{"innerStyle":{"text-align":"","font-size":"20px","color":""}}
Now the issue I am having is if I set a break point on my UpdateRecord Action and see what is coming through the innerStyle object is null. Can someone tell me where I am going wrong please.

I tried using the below code and it's working fine.
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
"color": "sample string 1",
"font-size": "sample string 2",
"font-family": "sample string 3"
}

#Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
$('#font-size-ddl').change(function () {
var value = $(this).val();
var headerObj = {};
headerObj["HeaderColor"] = "Red";
headerObj["HeaderFontSize"] = value;
headerObj["HeaderFontFamily"] = "Arial";
console.log(JSON.stringify({ custom: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Employee")",
traditional: true,
data: JSON.stringify({ custom: headerObj }),
dataType: JSON,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});

Related

Ajax call is posting 0 or null

Can't figure out this simple ajax call.
The controller successfully returns the json file as it should, but is logging two zeroes as the values for both the country and amount, which are incorrect. What am I doing wrong here?
controller:
[HttpPost("search")]
public IActionResult test(int country, int amount)
{
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
return Json("success : true");
}
jQuery:
var data = "{ 'country': 2, 'amount': 4}";
$.ajax({
url: "search",
type: "POST",
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
Create a model to hold the desired values
public class TestModel {
public int country { get; set; }
public decimal amount { get; set; }
}
Update the action to expect the data in the body of the request using [FromBody] attribute
[HttpPost("search")]
public IActionResult test([FromBody]TestModel model) {
if(ModelState.IsValid) {
var country = model.country;
var amount = model.amount;
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
return Ok( new { success = true });
}
return BadRequest(ModelState);
}
Client side you need to make sure the data is being sent in the correct format
var data = { country: 2, amount: 4.02 };
$.ajax({
url: "search",
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
Reference Model Binding in ASP.NET Core
You should use JSON.stringify to convert a object into a json string. Do not try to use string concatenation to do this.
Your types for amount do not match what you are sending. A money type should probably be decimal in c#.
Return an anonymous object from the c# method as well and pass that to Json.
The content-type is incorrect, see also What is the correct JSON content type?
[HttpPost("search")]
public IActionResult test(int country, decimal amount)
{
System.Console.WriteLine(country);
System.Console.WriteLine(amount);
// return an anymous object instead of a string
return Json(new {Success = true});
}
jQuery:
var data = JSON.stringify({country: 2, amount: 4.02});
$.ajax({
url: "search",
type: "POST",
dataType: 'json',
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});
What am I doing wrong here?
dataType is not required so you can omit that.
4.02 is not an int so you should probably replace that with decimal
and contentType should be application/json
Thanks everyone! Got it working with your help.
It won't work after I remove [FromBody]
[HttpPost("search")]
public IActionResult test([FromBody] string data)
{
System.Console.WriteLine(data);
return Json(new {Success = true});
}
jQuery:
var data = JSON.stringify("{ 'data': 'THOMAS' }");
$.ajax({
url: "search",
type: "POST",
data: data,
cache: false,
contentType: "application/json",
success: function (data) {
alert("hi"+ data);
}
});

data posted with jquery post to Asp.net 4 Mvc 2 as null

I am using jquery 1.8 to post data to ASP.Net 4 MVC 2 like this
PostData('Home/Login',{ "username": $("#username").val(),"password": $("#password").val()})
function PostData(url, data) {
$.ajax({
url: url,
data:data,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
My model
namespace FmsMvc.Models
{
public class UsersModel
{
public int UserID { get; set; }
public string Role { get; set; }
public string Email { get; set; }
public DateTime ts { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
My Controller
[HttpPost]
public JsonResult Login(UsersModel u)
{
if (doSomething(Prop1, Prop2)
return Json(null); // Success
return Json(new { Status:'success',Msg:" Your username"+u.username });
}
My controller does not get the data. It gets null when debugging.
what am i doing wrong?
NOTE
I deleted all the javascript in the Scripts folder, as I am using a custom script
Have you tried JSON.strinfigy-ing your data before POSTing?
function PostData(url, data) {
$.ajax({
url: url,
data:JSON.stringify(data),
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
Try it like this:
var data = { "username": $("#username").val(),
"password": $("#password").val()
};
PostData('Home/Login',JSON.stringify(data));
You can use the JQuery .post() method which will parse the values for you
var url = '#Url.Action("Login", "Home")'; // beter to use this rather than hardcoding
var userName = `$("#username").val();
var password = $("#password").val();
$.post(url, { Username: userName, Password: password }, function(result) {
// do something with the result you returned from the action method
alert(result.Msg);
});
Note, only properties Username and Password will be set in the model. The other properties will be their default values.
After much debugging, i found the culprit
in my ajax function above i have this two line
contentType: 'application/json; charset=utf-8',
dataType:'json',
Somehow, this should not be. when i submitted the form with the two lines present, this is what i saw in chrome dev
But when i removed the line contentType: 'application/json; charset=utf-8', so that the $.ajax is now
$.ajax({ // create an AJAX call...
type: 'post', // GET or POST
url: url, // the file to call
dataType:'json',
data: data, // get the form data
Success:successFunction, Error: ErrorFunction
});
when i look in chrome dev after submit, i see this, which was not there before
I dont' know why this is the case, i will try in other browsers to see if it all works

ajax pass object to controller

HomeController:
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(CategoryOrderModel categories)
{
return Json(new { msg = "ok" });
}
public class CategoryOrderModel
{
public int DisplayOrder;
public int CategoryId;
}
View:
var operationCollection = new CategoryOrderModel();
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: JSON.stringify(operationCollection),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
The controller never gets the correct parameter??
UPDATED: I changed the code to accept the collection
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(List<CategoryOrderModel> categories)
{
return Json(new { msg = 'ok' });
}
View:
var collection = [];
var col1= new CategoryOrderModel(1,2);
collection.push(col1);
var col2= new CategoryOrderModel(2,5);
collection.push(col2);
$.ajax({
url: '/Home/SetDefaultHomeCategoryOrder/',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(collection) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
function CategoryOrderModel(displayOrder, categoryId) {
var self = this;
self.DisplayOrder = displayOrder;
self.CategoryId = categoryId;
}
Following are the errors in your code
1.Your model dont have getters and setters
public class CategoryOrderModel
{
public int DisplayOrder { get; set; }
public int CategoryId { get; set; }
}
2.Since it is javascript , operationCollection is model so it will not work instead deaclare a variable
var CategoryOrderModel =
{
"DisplayOrder": "7",
"CategoryId": "9"
};
$.ajax({
url: '#Url.Action("SetCategoryOrder", "Home")',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(CategoryOrderModel) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
As we know MVC works on the principle of name/value pair i.e. on Strongly type view along with Model binding.
Possibly you can do:
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: {'DisplayOrder' : 9 , 'CategoryId' : 1},
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
Notice data key/value data: {'DisplayOrder' : 9 , 'CategoryId' : 1},, this is somewhat similar to post a form in MVC.
Generally we use $('#formId').serialize() to send collection from view to controller with jquery/ajax.
You are trying to pass the data to controller "SetDefaultHomeCategoryOrder" or "SetCategoryOrder"
if Action name is SetCategoryOrder then type
url:#Url.Action('SetCategoryOrder','Home')
Your methods don't match from view you are calling SetDefaultHomeCategoryOrder but inside the controller it's called SetCategoryOrder

Ajax to WCF, can't load Ajax into an object

I want to send some data back form my JavaScript to WCF. This object I send back needs to get loaded in the Foo class. If I debug the code I can see the function (Sting) gets called. But if i check whats in the the object I got returned, this object is null.
This indicates the data can't be stored in in the Object of WCF. The WCF works find when I send data to the JavaScript with Ajax. FYI I use .NET 3.5
this is how I try to receive the data: WCF:
namespace TPlatform
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataService
{
[OperationContract]
public void Sting(Foo postData)
{
var x = 1; //Breakpoint, postData is null?
}
}
[DataContract]
public class Foo
{
[DataMember]
public string Bar;
}
}
JavaScript:
var fooObject = { "Bar": "test" };
function sendDataToWcf(object) {
$.ajax({
type: "POST",
url: "DataService.svc/Sting",
data: JSON.stringify(fooObject),
processData: false,
contentType: "application/json",
dataType: "json",
success: suckcess,
error: showError
});
}
What am I doing wrong? How can I read the the data into my class?
Try this
$.ajax({
type: 'POST',
url: url,
//dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ postData: fooObject}),
success: function (response) {
successCallback(response);
},
error: function (xhr, status, error) {
handleError(xhr, status, error);
}
});
Update: Change:
var fooObject = { "Bar": "test" };
too
var fooObject = { Bar: "test" };
and dont send the datatype.

MVC4 cannot map object properties to JSON from AJAX POST

Model:
public class JsonRequest
{
public string Data { get; set; }
}
Action:
[HttpPost]
public ActionResult Index(JsonRequest data)
{
return new JsonResult()
{
Data = string.Format("Data: {0}", data.Data), // data.Data == null here
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
AJAX:
$.ajax({
type: 'POST',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
JsonRequest object has an instance in Index action but it's Data property was not mapped to the passed JSON. How can I achieve this?
You need to remove JSON.stringify() call, because jQuery do it itself. And according standarts it's better to write {"Data" : "Hello world"} ("Data" in quotes).
Well you are specifying data not Data when passing the object back up to the server. This may be the root of the problem. Also specify the contentType in your AJAX request.
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ Data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
http://api.jquery.com/jQuery.ajax/

Categories

Resources