Javascript passing null to an ExpandoObject field in C# Controller parameter











up vote
1
down vote

favorite












My Javascript Code



$('[step="4"]').click(function () {
//shortened for brevety
var _model = new Object();
_model.ItemDesc.value = 'Descript';
//^ throws an error but gets fixed if removing the .value
_model.ItemQty.num = 1;
_model.ItemQty.unit = 'pcs'

$.ajax({
type: "POST",
url: 'CreateItemCallAsync',
data: _model,
success: function (msg) {
status = JSON.stringify(msg);
alert('Item created successfully!');
location.reload();
},
error: function (msg) {
status = JSON.stringify(msg);
alert('Failed to create item.');
location.reload();
}
});
});


C# Controller Code



[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
//breakpoint here
var test = item.ItemDesc;
var qty = item.ItemQty.num; //getting nulls here
var unit = item.ItemQty.unit; //getting nulls here
}


C# CreateItemModel



public class CreateItemModel
{
public string ItemName { get; set; }
public string ItemDesc { get; set; }
public ExpandoObject ItemQty { get; set; }
}


JavaScript Object



[
{
ItemName : 'Item1',
ItemDesc : 'Descript'
ItemQty : { num : 5 , unit: 'pcs'}
},
{
ItemName : 'Item2',
ItemDesc : 'Descript'
ItemQty : { num : 1 , unit: 'box'}
}
]


From the code above. I have a JavaScript object passed to my C# controller with a CreateItemModel parameter that has a field of ItemQty as an ExpandoObject. However, after passing to my C# controller. the ItemQty.num and ItemQty.unit are null.



With further investigating, before passing the JavaScript object to C# controller. the Objects are successfully populated.



I need ItemQty as an ExpandoObject because the fields/properites under ItemQty is always changing/dynamic



Questions:




  1. (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.

  2. Why am I getting nulls in ItemQty properties?










share|improve this question
























  • Could you show use your receive JSON data?
    – D-Shih
    Nov 14 at 7:55












  • Add your CreateItemModel to the question
    – user3559349
    Nov 14 at 7:56






  • 1




    in the ajax request change the data: _model to data: { item: JSON.stringify(_model) } as your api end point is expecting the item object
    – Hassaan
    Nov 14 at 7:57












  • For point 1 - ItemDesc is typeof string - it does not have a property named value
    – user3559349
    Nov 14 at 8:06






  • 1




    You need to modify the data you are sending if you want to use a Dictionary (using the default contentType as you are doing, then it would be var _model = { ItemDesc.value: 'Descript', ItemQty[0].Key: 'num', ItemQty[0].Value: 1, ItemQty[1].Key: 'unit', ItemQty[1].Value: 'pcs' };
    – user3559349
    Nov 14 at 8:26















up vote
1
down vote

favorite












My Javascript Code



$('[step="4"]').click(function () {
//shortened for brevety
var _model = new Object();
_model.ItemDesc.value = 'Descript';
//^ throws an error but gets fixed if removing the .value
_model.ItemQty.num = 1;
_model.ItemQty.unit = 'pcs'

$.ajax({
type: "POST",
url: 'CreateItemCallAsync',
data: _model,
success: function (msg) {
status = JSON.stringify(msg);
alert('Item created successfully!');
location.reload();
},
error: function (msg) {
status = JSON.stringify(msg);
alert('Failed to create item.');
location.reload();
}
});
});


C# Controller Code



[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
//breakpoint here
var test = item.ItemDesc;
var qty = item.ItemQty.num; //getting nulls here
var unit = item.ItemQty.unit; //getting nulls here
}


C# CreateItemModel



public class CreateItemModel
{
public string ItemName { get; set; }
public string ItemDesc { get; set; }
public ExpandoObject ItemQty { get; set; }
}


JavaScript Object



[
{
ItemName : 'Item1',
ItemDesc : 'Descript'
ItemQty : { num : 5 , unit: 'pcs'}
},
{
ItemName : 'Item2',
ItemDesc : 'Descript'
ItemQty : { num : 1 , unit: 'box'}
}
]


From the code above. I have a JavaScript object passed to my C# controller with a CreateItemModel parameter that has a field of ItemQty as an ExpandoObject. However, after passing to my C# controller. the ItemQty.num and ItemQty.unit are null.



With further investigating, before passing the JavaScript object to C# controller. the Objects are successfully populated.



I need ItemQty as an ExpandoObject because the fields/properites under ItemQty is always changing/dynamic



Questions:




  1. (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.

  2. Why am I getting nulls in ItemQty properties?










share|improve this question
























  • Could you show use your receive JSON data?
    – D-Shih
    Nov 14 at 7:55












  • Add your CreateItemModel to the question
    – user3559349
    Nov 14 at 7:56






  • 1




    in the ajax request change the data: _model to data: { item: JSON.stringify(_model) } as your api end point is expecting the item object
    – Hassaan
    Nov 14 at 7:57












  • For point 1 - ItemDesc is typeof string - it does not have a property named value
    – user3559349
    Nov 14 at 8:06






  • 1




    You need to modify the data you are sending if you want to use a Dictionary (using the default contentType as you are doing, then it would be var _model = { ItemDesc.value: 'Descript', ItemQty[0].Key: 'num', ItemQty[0].Value: 1, ItemQty[1].Key: 'unit', ItemQty[1].Value: 'pcs' };
    – user3559349
    Nov 14 at 8:26













up vote
1
down vote

favorite









up vote
1
down vote

favorite











My Javascript Code



$('[step="4"]').click(function () {
//shortened for brevety
var _model = new Object();
_model.ItemDesc.value = 'Descript';
//^ throws an error but gets fixed if removing the .value
_model.ItemQty.num = 1;
_model.ItemQty.unit = 'pcs'

$.ajax({
type: "POST",
url: 'CreateItemCallAsync',
data: _model,
success: function (msg) {
status = JSON.stringify(msg);
alert('Item created successfully!');
location.reload();
},
error: function (msg) {
status = JSON.stringify(msg);
alert('Failed to create item.');
location.reload();
}
});
});


C# Controller Code



[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
//breakpoint here
var test = item.ItemDesc;
var qty = item.ItemQty.num; //getting nulls here
var unit = item.ItemQty.unit; //getting nulls here
}


C# CreateItemModel



public class CreateItemModel
{
public string ItemName { get; set; }
public string ItemDesc { get; set; }
public ExpandoObject ItemQty { get; set; }
}


JavaScript Object



[
{
ItemName : 'Item1',
ItemDesc : 'Descript'
ItemQty : { num : 5 , unit: 'pcs'}
},
{
ItemName : 'Item2',
ItemDesc : 'Descript'
ItemQty : { num : 1 , unit: 'box'}
}
]


From the code above. I have a JavaScript object passed to my C# controller with a CreateItemModel parameter that has a field of ItemQty as an ExpandoObject. However, after passing to my C# controller. the ItemQty.num and ItemQty.unit are null.



With further investigating, before passing the JavaScript object to C# controller. the Objects are successfully populated.



I need ItemQty as an ExpandoObject because the fields/properites under ItemQty is always changing/dynamic



Questions:




  1. (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.

  2. Why am I getting nulls in ItemQty properties?










share|improve this question















My Javascript Code



$('[step="4"]').click(function () {
//shortened for brevety
var _model = new Object();
_model.ItemDesc.value = 'Descript';
//^ throws an error but gets fixed if removing the .value
_model.ItemQty.num = 1;
_model.ItemQty.unit = 'pcs'

$.ajax({
type: "POST",
url: 'CreateItemCallAsync',
data: _model,
success: function (msg) {
status = JSON.stringify(msg);
alert('Item created successfully!');
location.reload();
},
error: function (msg) {
status = JSON.stringify(msg);
alert('Failed to create item.');
location.reload();
}
});
});


C# Controller Code



[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
//breakpoint here
var test = item.ItemDesc;
var qty = item.ItemQty.num; //getting nulls here
var unit = item.ItemQty.unit; //getting nulls here
}


C# CreateItemModel



public class CreateItemModel
{
public string ItemName { get; set; }
public string ItemDesc { get; set; }
public ExpandoObject ItemQty { get; set; }
}


JavaScript Object



[
{
ItemName : 'Item1',
ItemDesc : 'Descript'
ItemQty : { num : 5 , unit: 'pcs'}
},
{
ItemName : 'Item2',
ItemDesc : 'Descript'
ItemQty : { num : 1 , unit: 'box'}
}
]


From the code above. I have a JavaScript object passed to my C# controller with a CreateItemModel parameter that has a field of ItemQty as an ExpandoObject. However, after passing to my C# controller. the ItemQty.num and ItemQty.unit are null.



With further investigating, before passing the JavaScript object to C# controller. the Objects are successfully populated.



I need ItemQty as an ExpandoObject because the fields/properites under ItemQty is always changing/dynamic



Questions:




  1. (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.

  2. Why am I getting nulls in ItemQty properties?







javascript c# asp.net-mvc json.net expando






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 at 8:03

























asked Nov 14 at 7:53









Hexxed

485317




485317












  • Could you show use your receive JSON data?
    – D-Shih
    Nov 14 at 7:55












  • Add your CreateItemModel to the question
    – user3559349
    Nov 14 at 7:56






  • 1




    in the ajax request change the data: _model to data: { item: JSON.stringify(_model) } as your api end point is expecting the item object
    – Hassaan
    Nov 14 at 7:57












  • For point 1 - ItemDesc is typeof string - it does not have a property named value
    – user3559349
    Nov 14 at 8:06






  • 1




    You need to modify the data you are sending if you want to use a Dictionary (using the default contentType as you are doing, then it would be var _model = { ItemDesc.value: 'Descript', ItemQty[0].Key: 'num', ItemQty[0].Value: 1, ItemQty[1].Key: 'unit', ItemQty[1].Value: 'pcs' };
    – user3559349
    Nov 14 at 8:26


















  • Could you show use your receive JSON data?
    – D-Shih
    Nov 14 at 7:55












  • Add your CreateItemModel to the question
    – user3559349
    Nov 14 at 7:56






  • 1




    in the ajax request change the data: _model to data: { item: JSON.stringify(_model) } as your api end point is expecting the item object
    – Hassaan
    Nov 14 at 7:57












  • For point 1 - ItemDesc is typeof string - it does not have a property named value
    – user3559349
    Nov 14 at 8:06






  • 1




    You need to modify the data you are sending if you want to use a Dictionary (using the default contentType as you are doing, then it would be var _model = { ItemDesc.value: 'Descript', ItemQty[0].Key: 'num', ItemQty[0].Value: 1, ItemQty[1].Key: 'unit', ItemQty[1].Value: 'pcs' };
    – user3559349
    Nov 14 at 8:26
















Could you show use your receive JSON data?
– D-Shih
Nov 14 at 7:55






Could you show use your receive JSON data?
– D-Shih
Nov 14 at 7:55














Add your CreateItemModel to the question
– user3559349
Nov 14 at 7:56




Add your CreateItemModel to the question
– user3559349
Nov 14 at 7:56




1




1




in the ajax request change the data: _model to data: { item: JSON.stringify(_model) } as your api end point is expecting the item object
– Hassaan
Nov 14 at 7:57






in the ajax request change the data: _model to data: { item: JSON.stringify(_model) } as your api end point is expecting the item object
– Hassaan
Nov 14 at 7:57














For point 1 - ItemDesc is typeof string - it does not have a property named value
– user3559349
Nov 14 at 8:06




For point 1 - ItemDesc is typeof string - it does not have a property named value
– user3559349
Nov 14 at 8:06




1




1




You need to modify the data you are sending if you want to use a Dictionary (using the default contentType as you are doing, then it would be var _model = { ItemDesc.value: 'Descript', ItemQty[0].Key: 'num', ItemQty[0].Value: 1, ItemQty[1].Key: 'unit', ItemQty[1].Value: 'pcs' };
– user3559349
Nov 14 at 8:26




You need to modify the data you are sending if you want to use a Dictionary (using the default contentType as you are doing, then it would be var _model = { ItemDesc.value: 'Descript', ItemQty[0].Key: 'num', ItemQty[0].Value: 1, ItemQty[1].Key: 'unit', ItemQty[1].Value: 'pcs' };
– user3559349
Nov 14 at 8:26












1 Answer
1






active

oldest

votes

















up vote
1
down vote














(Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.




Because there isn't a property ItemDesc,ItemQty,ItemQty in original javascript Object.



You can try to create an anonymous JSON object for your javascript code.



var _model = {     
ItemDesc: {
value : "Descript"
},
ItemQty :{
num : 1,
unit :'pcs'
}
};


instead of



var _model = new Object();
_model.ItemDesc.value = 'Descript';
_model.ItemQty.num = 1;
_model.ItemQty.unit = 'pcs'


your c# model might look like because your currently ItemDesc is an object instead of a string value.




Why am I getting nulls in ItemQty properties?




Because default ModelBindiner can't find ExpandoObject with your JSON key ItemQty object.



public class ItemDesc
{
public string value { get; set; }
}

public class ItemQty
{
public int num { get; set; }
public string unit { get; set; }
}

public class CreateItemModel
{
public ItemDesc ItemDescContext { get; set; }
public ItemQty ItemQtyContext { get; set; }
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295349%2fjavascript-passing-null-to-an-expandoobject-field-in-c-sharp-controller-paramete%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote














    (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.




    Because there isn't a property ItemDesc,ItemQty,ItemQty in original javascript Object.



    You can try to create an anonymous JSON object for your javascript code.



    var _model = {     
    ItemDesc: {
    value : "Descript"
    },
    ItemQty :{
    num : 1,
    unit :'pcs'
    }
    };


    instead of



    var _model = new Object();
    _model.ItemDesc.value = 'Descript';
    _model.ItemQty.num = 1;
    _model.ItemQty.unit = 'pcs'


    your c# model might look like because your currently ItemDesc is an object instead of a string value.




    Why am I getting nulls in ItemQty properties?




    Because default ModelBindiner can't find ExpandoObject with your JSON key ItemQty object.



    public class ItemDesc
    {
    public string value { get; set; }
    }

    public class ItemQty
    {
    public int num { get; set; }
    public string unit { get; set; }
    }

    public class CreateItemModel
    {
    public ItemDesc ItemDescContext { get; set; }
    public ItemQty ItemQtyContext { get; set; }
    }





    share|improve this answer



























      up vote
      1
      down vote














      (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.




      Because there isn't a property ItemDesc,ItemQty,ItemQty in original javascript Object.



      You can try to create an anonymous JSON object for your javascript code.



      var _model = {     
      ItemDesc: {
      value : "Descript"
      },
      ItemQty :{
      num : 1,
      unit :'pcs'
      }
      };


      instead of



      var _model = new Object();
      _model.ItemDesc.value = 'Descript';
      _model.ItemQty.num = 1;
      _model.ItemQty.unit = 'pcs'


      your c# model might look like because your currently ItemDesc is an object instead of a string value.




      Why am I getting nulls in ItemQty properties?




      Because default ModelBindiner can't find ExpandoObject with your JSON key ItemQty object.



      public class ItemDesc
      {
      public string value { get; set; }
      }

      public class ItemQty
      {
      public int num { get; set; }
      public string unit { get; set; }
      }

      public class CreateItemModel
      {
      public ItemDesc ItemDescContext { get; set; }
      public ItemQty ItemQtyContext { get; set; }
      }





      share|improve this answer

























        up vote
        1
        down vote










        up vote
        1
        down vote










        (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.




        Because there isn't a property ItemDesc,ItemQty,ItemQty in original javascript Object.



        You can try to create an anonymous JSON object for your javascript code.



        var _model = {     
        ItemDesc: {
        value : "Descript"
        },
        ItemQty :{
        num : 1,
        unit :'pcs'
        }
        };


        instead of



        var _model = new Object();
        _model.ItemDesc.value = 'Descript';
        _model.ItemQty.num = 1;
        _model.ItemQty.unit = 'pcs'


        your c# model might look like because your currently ItemDesc is an object instead of a string value.




        Why am I getting nulls in ItemQty properties?




        Because default ModelBindiner can't find ExpandoObject with your JSON key ItemQty object.



        public class ItemDesc
        {
        public string value { get; set; }
        }

        public class ItemQty
        {
        public int num { get; set; }
        public string unit { get; set; }
        }

        public class CreateItemModel
        {
        public ItemDesc ItemDescContext { get; set; }
        public ItemQty ItemQtyContext { get; set; }
        }





        share|improve this answer















        (Bit of off topic) why _model.ItemDesc.value = 'Descript' errors? On the other hand _model.ItemDesc = 'Descript' runs without error.




        Because there isn't a property ItemDesc,ItemQty,ItemQty in original javascript Object.



        You can try to create an anonymous JSON object for your javascript code.



        var _model = {     
        ItemDesc: {
        value : "Descript"
        },
        ItemQty :{
        num : 1,
        unit :'pcs'
        }
        };


        instead of



        var _model = new Object();
        _model.ItemDesc.value = 'Descript';
        _model.ItemQty.num = 1;
        _model.ItemQty.unit = 'pcs'


        your c# model might look like because your currently ItemDesc is an object instead of a string value.




        Why am I getting nulls in ItemQty properties?




        Because default ModelBindiner can't find ExpandoObject with your JSON key ItemQty object.



        public class ItemDesc
        {
        public string value { get; set; }
        }

        public class ItemQty
        {
        public int num { get; set; }
        public string unit { get; set; }
        }

        public class CreateItemModel
        {
        public ItemDesc ItemDescContext { get; set; }
        public ItemQty ItemQtyContext { get; set; }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 at 8:07

























        answered Nov 14 at 8:01









        D-Shih

        24.6k61431




        24.6k61431






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295349%2fjavascript-passing-null-to-an-expandoobject-field-in-c-sharp-controller-paramete%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

            How to change which sound is reproduced for terminal bell?

            Can I use Tabulator js library in my java Spring + Thymeleaf project?