2

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?

3

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.