1

======================

Part 2

MVC controler's field1 always has null (Post([FromBody] TestModel field1) ) null values if I use JSON.stringify(MyDdata). Even on the simplest JSON strings.

I used an XML to JSON convert to make sure my JSON data was correct. (I still need to get to know JSON.) I would think the following would be easily consume by the MVC controller but the input parameter field1 is null. At the least, TestStrng & TestStrng2 should have values.

The controller isn't crashing but it isn't understanding the JSON either.

Why doesn't the MVC Controler know the JSON class?

//JavaScript
var MyDdata = 
{
    "TestModel": {
        "TestStrng": "Scott",
        "TestStrng2": "SomethingElse",
        "Usr": { "UsrToken": "aaaa" },
        "LstSubClass": {
            "SubClass": [
            { "FirstName": "Beth" },
            { "FirstName": "Julie" },
            { "FirstName": "John" }
            ]
        }
    }
}
sdata = JSON.stringify(MyDdata);
$.ajax({
    type: 'post',
    url: serviceUrl,
    cache: false,
    data: sdata,
    dataType: "json",
}).done(function (data) {


//C# Class
public class Usr
{
    public string UsrToken { get; set; }
}
public class SubClass
{
    public string FirstName { get; set; }
}
public class TestModel // Main\Master Class
{
    public string TestStrng { get; set; }
    public string TestStrng2 { get; set; }

    public List<SubClass> LstSubClass = new List<SubClass>();

    private Usr _Usr = new Usr();
    public Usr oUsr
    {
        get { return _Usr; }
        set { _Usr = value; }
    }
}

//MVC Controller
[System.Web.Http.Description.ResponseType(typeof(TestModel))]
public HttpResponseMessage Post([FromBody] TestModel field1)
{
// ...
}

//XML Data
<TestModel>
    <TestStrng>Scott</TestStrng>
    <TestStrng2>SomethingElse</TestStrng2>
    <Usr>
        <UsrToken>aaaa</UsrToken>
    </Usr>
    <LstSubClass>
        <SubClass><FirstName>Beth</FirstName></SubClass>
        <SubClass><FirstName>Julie</FirstName></SubClass>
        <SubClass><FirstName>John</FirstName></SubClass>
    </LstSubClass>
</TestModel>

JSON Data
{
  "TestModel": {
    "TestStrng": "Scott",
    "TestStrng2": "SomethingElse",
    "Usr": { "UsrToken": "aaaa" },
    "LstSubClass": {
      "SubClass": [
        { "FirstName": "Beth" },
        { "FirstName": "Julie" },
        { "FirstName": "John" }
      ]
    }
  }
}

======================

Part 1

I am trying to learn Web API in C# and have spent a day on this one problem. The problem is in JavaScript with "data: ...".

hardcoded this works

Ajax data: {'TestStrng': 'one', 'TestStrng2': 'two' }

Below in the controller, as expected, the p_TestModel contains the values 'one' & 'two'. public HttpResponseMessage Post(TestModel p_TestModel) BUT the data is NOT passed from JS to Controller if I use a variable like data: sdata.

I have tried tens of ways and many I am too embarrassed to write:

var sdata = "'TestStrng': 'one', 'TestStrng2': 'two'";
sdata = "'TestStrng': 'one'";
var jsonString = JSON.stringify(sdata);
JSON.stringify(sdata); {
  'TestStrng': 'one',
  'TestStrng2': 'two'
}, {
  'TestStrng': 'one',
  'TestStrng2': 'two'
}, {
  field1: "hello"
},
data: {
    sdata
  },
  'TestStrng': 'onetwo'
},
"{ 'TestModel': { 'TestStrng': 'one', 'TestStrng2': 'two' } }",
JSON.stringify(sdata),
  sdata,
  sdata = "'TestStrng': 'one', 'TestStrng2': 'two'";
data: {
  TestModel,
  sdata
},

Question

What am I doing wrong? Why won't a JS variable send the data so the controller can see it as if it is hardcoded?

C# class

public class TestModel {
  public string TestStrng { get; set; }
  public string TestStrng2 { get; set; }
}

MVC Controller

[System.Web.Http.Description.ResponseType(typeof(TestModel))]
public HttpResponseMessage Post(TestModel p_TestModel)
{
   // p_TestModel has correct values if hardcoded in JS.
   // It is ALWAYS null if JS uses a variable (sData) to send it.
   ...
}

JavaScript

$.ajax({
    type: 'post',
    url: serviceUrl,
    cache: false,
    dataType: "json",
    data: sdata, <<<<<<<<<<????
}).done(function (data) {
JenniferWalters
  • 87
  • 1
  • 11

1 Answers1

2

Create a javascript object and use that. This should work.

var sdata= { TestStrng :"Scott",TestStrng2:"SomethingElse" };
$.ajax({
    type: 'post',
    url: serviceUrl,      
    data: sdata
}).done(function (data) { console.log(data) });

If your view model is a flat view model without any complex navigational properties, the above code will work fine. But if you have complex properties on your view model, You need to convert the js object to a JSON String and set the contentType property

var model= { Name:"S",Address: { City:"Detroit"} };
$.ajax({
    type: 'post',
    url: serviceUrl,      
    data: JSON.stringify(model),
    contentType: "application/json"
}).done(function (data) { console.log(data) });

Take a look at this answer explaining different approaches for sending data from your client js code to your web api endpoint.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Thanks for your reply. I read the link you provided [and a hundred other ones :) ]. But I am not getting any further along for DYNAMIC input parameters. JSON.stringify(MyDdata) just doesn't seem to work for me. – JenniferWalters Jan 01 '16 at 16:25