0

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.

Izzy
  • 6,740
  • 7
  • 40
  • 84
  • Seems like [JsonProperty] is from Newtonsoft.Json. Asp.net controller doesn't support it – Danil Eroshenko Sep 14 '17 at 09:05
  • @DanilEroshenko So what other option do I have to achieve what I am trying to achieve? – Izzy Sep 14 '17 at 09:06
  • you can look at Model Binder.. In short the data should be available in Request itself. – user2580925 Sep 14 '17 at 09:07
  • If you want to use newtonsoft.json, you should probably look at MVC ModelBinder – Danil Eroshenko Sep 14 '17 at 09:09
  • Look at this question: https://stackoverflow.com/questions/23995210/how-to-use-json-net-for-json-modelbinding-in-an-mvc5-project – Danil Eroshenko Sep 14 '17 at 09:10
  • You can simply change the controller signature to this: `public JsonResult UpdateRecord(string innerStyle)` and deserialize the string inside the method using Json.Net. – Ardit Sep 14 '17 at 09:11
  • @Ardit It still does send anything back I have already tried that. – Izzy Sep 14 '17 at 09:13
  • @DanilEroshenko I don't have to use newtonsoft,json if there is another way – Izzy Sep 14 '17 at 09:14
  • @Code have you tried without the JSON.stringify but sending directly the object? – Ardit Sep 14 '17 at 09:16
  • @Code even your propery doesn't match object c# with object javascript (font-family <-> text-align) – Ardit Sep 14 '17 at 09:19
  • Try [DataMember(Name="somename")] – Danil Eroshenko Sep 14 '17 at 09:19
  • @DanilEroshenko That does not work either – Izzy Sep 14 '17 at 09:28
  • @Ardit I have a property in my object I did not include it in the question – Izzy Sep 14 '17 at 09:28
  • Try adding the propery to the Ajax call: `datatype: 'json'` before the contentType using `data: JSON.stringify({ innerStyle: headerObj}),` – Ardit Sep 14 '17 at 09:37
  • @Code then I bet it uses System.Web.Script.Serialization.JavaScriptSerializer that doesn't support DataMember properties (as DataContractJsonSerializer does). So you need to use ModelBinding anyway. You can try it with DataContractJsonSerializer instead of Newtonsoft.Json – Danil Eroshenko Sep 14 '17 at 09:38
  • 1
    You don't need to use the key while passing data to a controller `data: JSON.stringify(headerObj)` given `headerObj` is an object similar to your model `InnerStyke` – Abdul Samad Sep 14 '17 at 11:17

2 Answers2

0

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"
}
Vijay
  • 247
  • 1
  • 2
  • 11
0

@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);
        }
    });
});
Archana Parmar
  • 558
  • 3
  • 13