Dnyaneshwari Barkase
Dnyaneshwari Barkase

Reputation: 31

How to pass dictionary item from client side (Ajax) to server side (MVC API)

I want to pass multiple key and value pair of dictionary type from client side using post method to server side which is MVC Web API HTTP get method.

   function FileSenderAPI(){
            var DictionaryData = new Object;
            DictionaryData = document.getElementById("hidFilePath").value;
            var Url = '<%=System.Configuration.ConfigurationManager.AppSettings["FileSenderAPI"].To String() %>';
            $.ajax({
                url: Url,
                method: 'Get',
                data Type: "json",
                data: {
                    ModelsPath:JSON.stringify(DictionaryData),
                    Exchange: exchange,
                    Exchange_key: key,
                },
                success: function (data, textStatus, xhr) {
                    alert(data);
                },
}
public HttpResponseMessage ConvertModel(Dictionary<string, string> ModelsPath,string Exchange,string Exchange_key)
{
} // its my API method.``

Upvotes: 1

Views: 286

Answers (1)

Tomato32
Tomato32

Reputation: 2245

Here is a solution. You can try it. Hope to help, my friend :))

1) Create a model

public class DictionaryModel
    {
        public Dictionary<string, string> dict { get; set; }
        public string Exchange { get; set; }
        public string Exchange_Key { get; set; }

    }

2) Action

        [HttpPost]
        public JsonResult Example(DictionaryModel model)
        {
            // Your Logic
            return Json("Success");
        }

3) In View

$('#btClick').on('click', function () {
                var dict = {};
                dict["id"] = "200";
                dict["Name"] = "Chris";
                dict["DynamicItem1"] = "Item 1";


                var theObject = {};
                theObject.dict = dict;
                theObject.Exchange = "Abc";
                theObject.Exchange_Key = "123";

                let url = '@Url.Action("Example","Home")';
                $.post( url, theObject, function (data, textStatus, XMLHttpRequest) {
                    console.log("success");
                }, "json");
            });

Upvotes: 1

Related Questions