简体   繁体   中英

How to pass a json object to a mvc controller

I want to be able pass 2 arguments to my controller. An id and an object[].

Here is my controller:

[HttpPost]
        public string SaveCoordinates(string Id, object[] pFrame) 
        {

            string rslt = "ERROR";
            if (pFrame != null)
            {
                try
                {
                    List<Coordinates> pList = new List<Coordinates>();
                    for (int i = 0; i < pFrame.Length; i++)
                    {
                        Dictionary<string, object> kvps = (Dictionary<string, object>)pFrame[i];
                        pList.Add(new Coordinates
                        {
                            Position = Convert.ToInt32(kvps["position"]),
                            Height = Convert.ToInt32(kvps["height"]),
                            Width = Convert.ToInt32(kvps["width"]),
                            Top = Convert.ToInt32(kvps["top"]),
                            Left = Convert.ToInt32(kvps["left"])
                        });
                    }

                    MongoDBSaveOneFrameCoordinates(Id, pList);
                    rslt = "SUCCESS";
                }
                catch (Exception ex)
                {
                }
                //foreach (Coordinates c in pFrame)
                //{
                //    string asdf;
                //}
            }
            return rslt;
        }

I know the way i wrote the method may not be correct, but im just confused on how I can pass both a string id and the object in an ajax call. Here is my ajax call:

$.ajax({
                    url: '/Member/SaveCoordinates/@Model.Id',
                    type: "POST",
                    data: window.image.pinpoints,
                    success: function (data) {

                       alert(data);
                    },
                    error: function () {

                        alert("error");
                    }
                });


                return false;
            });
      });

The @Model.Id is suppose to be the id that I want to pass into the "Id" parameter of my controller, and the window.image.pinpoints is the object I wanna pass through the "pFrame" object. How can i successfully do this so both parameters get passed in correctly? I think it may have something to do with the way I write the ajax jquery function.

Try this

data: {pFrame : JSON.stringify(window.image.pinpoints)},

in your ajax post

data: { pFrame: JSON.stringify(window.image.pinpoints), Id: modelId }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM