How to pass a javascript object to a C# MVC 4 controller

34,237

Solution 1

  1. Make sure the property names match between the javascript and the C# model. In your question you had Propr1 and Propr2 for the javascript object, but in the C# model you had Prop1 and Prop2 (missing the "r").
  2. Do not stringify the data before sending it, and do not set dataType to json. MVC can parse just fine with a collection of post parameters without the json serialization in your code.
  3. Omit the contentType, it is not necessary. WebAPI should autodetect this. You can leave it, but it's extraneous.
  4. Make sure the model properties are public.

Javascript Client side:

    var myData = {Prop1: '', Prop2: ''}; // #1
    $.ajax({
        type: 'POST',
        data: myData, // #2
        url: '/Home/SubmitMyData',
        //contentType: 'application/json', #3
        //dataType: 'json', #2
        success: alert('Youhou'),
        error: alert('not good')
    });

C# Server side method:

    public ActionResult SubmitMyData(MyParamModel myParam)
    {
        // Do my stuff here with my parameter
        return View();
    }

    public class MyParamModel // #4
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
    }

Solution 2

The value you pass for the data property should be an object, not a string:

data: myData,

the property names need to match:

var myData = { Prop1: '', Prop2: ''};

you need to use the [FromBody] attribute on your parameter value:

public ActionResult SubmitMyData([FromBody] MyParamModel myParam)

and the properties on your model type need to be public:

public class MyParamModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}
Share:
34,237
Régis NIOX
Author by

Régis NIOX

Software engineer technologically open minded: only cares about the fun :)

Updated on August 01, 2022

Comments

  • Régis NIOX
    Régis NIOX almost 2 years

    In MVC4, how do you pass a javascript object to a C# controller in AJAX? Finally I tried this but it did not work.

    Javascript Client side:

        var myData = {Propr1: '', Propr2: ''};
        $.ajax({
            type: 'POST',
            data: JSON.stringify(myData),
            url: '/Home/SubmitMyData',
            contentType: 'application/json',
            dataType: 'json',
            success: alert('Youhou'),
            error: alert('not good')
        });
    

    C# Server side method:

        public ActionResult SubmitMyData(MyParamModel myParam)
        {
            // Do my stuff here with my parameter
            return View();
        }
    
        public class MyParamModel
        {
            string Prop1 { get; set; }
            string Prop2 { get; set; }
        }
    

    My parameter is always null. I tried to change the contentType but it still not work. Where are my mistakes? I found some posts but I did not find what I did wrong.

    Thanks a lot.

  • RubberChickenLeader
    RubberChickenLeader over 9 years
    Can you post a small explination of what was wrong and why your code works?
  • David L
    David L over 9 years
    I do not think the FromBody attribute appropriate here. The OP is using MVC 4, not Web API.
  • danludwig
    danludwig over 9 years
    @DavidL thanks for pointing that out, I thought this was a WebAPI question due to the title.
  • David L
    David L over 9 years
    @danludwig Good point. Perhaps the OP should adjust the title a bit :).
  • Régis NIOX
    Régis NIOX over 9 years
    Sorry for the title. I tried again and it not worked for me :s My parameter is still null
  • danludwig
    danludwig over 9 years
    @NioxyBrown no worries I gave it a better title.
  • Régis NIOX
    Régis NIOX over 9 years
    I just found my mistake: I totally forgot to make the properties of my model "public" (my bad, @JLRishe and you wrote it...). Thanks a lot for your help!
  • jleach
    jleach about 8 years
    I'm surprised this doesn't have more upvotes... excellent answer
  • Admin
    Admin over 6 years
    Thankyou very much @danludwig
  • FerhatA
    FerhatA over 4 years
    @danludwig Senior Developer in my team forgot to add set and get and that cost me 1 whole day to solve Thank You