Post JSON array to mvc controller

前端 未结 3 1120
遇见更好的自我
遇见更好的自我 2020-12-01 12:48

I\'m trying to post a JSON array to an MVC controller. But no matter what I try, everything is 0 or null.

I have this table that contains textboxes. I need from all

3条回答
  •  粉色の甜心
    2020-12-01 13:20

    There is another simpler way: using Query String to send your data. If you got intrested, your current approach is wrong because the JSON array data type is string not CustomTypeModel.

    First of all, remove the data ajax option. We don't need that anymore.

    Second, change your controller like the following:

    [HttpPost]
    public ActionResult Update(string json)
    {
        // this line convert the json to a list of your type, exactly what you want.
        IList ctm = 
             new JavaScriptSerializer().Deserialize>(json);
    
        return RedirectToAction("Index");
    }
    

    Note1: It's important that names of your CustomTypeModel properties be the same as what you enter as the JSON elements. So, your CustomTypeModel should be like this:

    public class CustomTypeModel
    {
        // int, or maybe string ... whatever you want.
        public int TransIDs { get; set; }
        public int ItemIDs { get; set; }
        public int TypeIDs { get; set; }
    }
    

    Note2: This approach is useful when you want to send the data through query strings. So, your url can be like this:

    url: '/controller/action?json=' + JSON.stringify(trans)
    

提交回复
热议问题