mathinvalidnik
mathinvalidnik

Reputation: 1600

How to send javascript dictionary to controller method in MVC4

I have a js file that has to send a dictionary object to the server. My javascript part looks like that:

$.ajax({
            url: "/ControllerName/ActionName",
            type: 'post',
            dataType: 'json',
            data: myData
        });

where myData is something like

this myData["favouritePet"] = "dog", myData["favouriteBook"] = "What?"

In the controller I have this:

[HttpPost]
public virtual ActionResult ActionName ( Dictionary<string, string> jsonFormattedData)
{


    return null;
}

but when I debug it the parameter gets a null value every time. I tried to make the argument of type string but it is the same. Can you help me with that?

Upvotes: 2

Views: 2893

Answers (1)

Win
Win

Reputation: 62311

You are just passing JavaScript object, so you can use JSON.stringify and make the Model as Action parameter.

MVC Model Binder will convert it to your model.

enter image description here

public class MyDataModel
{
    public string FavouritePet { get; set; }
    public string FavouriteBook { get; set; }
}

// GET: Home
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(MyDataModel myData)
{
    return View();
}

<button id="btnSubmit" type="button">Submit</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
    $("#btnSubmit").click(function () {
        var myData = new Object();
        myData.favouritePet = "dog";
        myData.favouriteBook = "What?";

        $.ajax({
            url: '@Url.Action("Index", "Home")',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(myData),
            contentType: "application/json; charset=utf-8",
            success: function (){}
        });
    });
</script>

Upvotes: 1

Related Questions