views:

330

answers:

3

I am wanting to pass a dictionary of type <int,int> to my controller via an Ajax post. The main reason here is the post may have between 1-3 key value pairs here (none of these values are known at compile time) and in the future it may go up to 5.

Also in the post I have to pass in some other data, such as Id and name, which all works as normal.

How would I construct this dictionay in the javascript then send it via the JQuery post and finally receive it on the controller to process?

Edit 2: I have decided to just solve this with a post for each value instead of trying to pass a dictionary.

EDIT: Here is my source for the function so you can see what I am trying:

function BindAddMenuItem() {
        $(".AddMenuItem").click(function (e) {
            e.preventDefault();

            //get header id from link by removing addmenuitem from this.id
            var currentId = $(this).attr("id").replace("AddMenuItem", "");

            //get itemnumber, itemname, itemdetails from textboxes with same header id
            var restaurantId = jQuery.trim($("#RestaurantId").val());
            var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
            var itemName = jQuery.trim($("#ItemName" + currentId).val());
            var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());

            var costs = new Object();
            //select all textboxes with class "Header" + currentId
            $(".Header" + currentId).each(function (i) {
                var optionId = $(this).attr("id").replace("Option", "");
                costs[optionId] = $(this).val();
            });


            $.ajax(
            {
                type: "POST",
                url: "/Menu/AddMenuItem",
                data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails + "&costs=" + costs,
                dataType: "html",
                success: function (result) {
                    var domElement = $(result);
                    $("#MenuContainer").replaceWith(domElement);
                    var newNum = parseInt(itemNumber) + 1;
                    $("#ItemNumber" + currentId).val(newNum);
                    BindAllBehaviours();
                }
            });
        });

    }
+3  A: 

Something like (javascript)

dict = new Object();
dict['12'] = 5;
dict['13'] = 6;
dict['1000'] = 21;
dict['9'] = 13;
dict['13'] = 48;

$.post('/client.mvc/mypostaction/', { myDictionary: dict });

You can then post the dict object to your controller using a Dictionary<int, int> as property type.

ActionResult MyPostAction(Dictionary<string, int> myDictionary)

edit from author's code second time:

The following works for me, when having a Dictionary<string, int> kvPairs. <int, int> isn't going to work after all.

Make your post like:

var dict = new Object();
dict['13'] = 9;
dict['14'] = 10;
dict['2'] = 5;

$.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); }); 
Jan Jongboom
When passing the dictionary like you suggest I get a null object. I have updated my question to show my source. Thanks
dean nolan
Check my edit .
Jan Jongboom
I have now tried the dictionary as string, int and string, string. Changed the post to how you list it and it still doesn't show any values. Thanks for the help so far. I don't really know how else to get this working
dean nolan
Check my edit. Have you surrounded the dictionary items with `'`?
Jan Jongboom
A: 

Client (JavaScript):

var dict = new Object(); dict.Key1 = "Value1" dict.Key2 = "Value2"

$.post('/YourController/YourAction/', dict);

NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.

Server:

public ActionResult YourAction() { string postData = string.Empty; using (StreamReader sr = new StreamReader(Request.InputStream)) { postData = sr.ReadToEnd(); }

//Load post data into JObject (Newtonsoft.Json) JObject o = JObject.Parse(postData);

//Extract each key/val string val1 = (string)o["Key1"];

//Do whatever....

}

VajNyiaj
A: 

Hi ActionResult MyPostAction(Dictionary myDictionary)

Will that work exactly same?

where as I i have captured <% var worksheets = (IDictionary) ViewData["WorkSheets"];%>

using ajaxform

Thanks

kazim