【问题标题】:Post Json Dictionary to the controller将 Json 字典发布到控制器
【发布时间】:2015-05-02 14:33:31
【问题描述】:

我的 jQuery 文件中有以下代码

var bases = {};
for (var j = 0; j < selectedVariants.length; j++) {
     bases[selectedVariants[j].BId] = selectedVariants[j].CId;
}

我现在正在基础字典中获取一些数据

我的问题是如何通过 ajax 调用将此基础字典传递给控制器​​。

我尝试了以下方法,但控制器中的碱基计数为零

$.ajax({
    url: $.url('~/TUP/Tflow'),
    type: 'POST',
    data: { baseDetails: JSON.stringify(bases)},
    async: true,
    cache: false,
});

当我在我的控制器中看到...碱基数为零时

请帮帮我

控制器:

[HttpPost]
public JsonResult Tflow(JsonFileContentInputs basedetails)
{   
    //some code   
}

还有我的模特:

[ModelBinder(typeof(JsonModelBinder))]
[DataContract]
public class JsonFileContentInputs
{
    [JsonProperty(PropertyName = "basedetails")]
    [DataMember]
    public Dictionary<string, string> basedetails { get; set; }              
}

【问题讨论】:

  • 你能发布你的控制器代码吗?
  • 您不需要对其进行字符串化,该函数应注意将其转换为 JSON。这更多地取决于您的控制器的配置方式。您使用的是什么服务器端技术?
  • 或者fiddle?
  • 感谢您的回复..控制器:[HttpPost] public JsonResult Tflow(JsonFileContentInputs basedetails) { //一些代码}和我的模型:[ModelBinder(typeof(JsonModelBinder))] [DataContract] 公共类JsonFileContentInputs { [JsonProperty(PropertyName = "basedetails")] [DataMember] public Dictionary basedetails { get;放; } }
  • 试试这样:data: JSON.stringify({ baseDetails: bases}),

标签: c# jquery ajax json model-view-controller


【解决方案1】:

尝试以下方法。正如@EhsanSajjad 所述,您需要对所有数据调用JSON.stringify,而不仅仅是bases 对象:

$.ajax({
    url: '/TUP/Tflow',
    type: 'POST',
    data: "json=" + JSON.stringify({baseDetails: bases}), // stringify everything,
    dataType: 'text',
    async: true,
    cache: false
});

然后在您的控制器中,我们可以使用 Json.NET 自己反序列化数据,而不是尝试使用模型绑定。

控制器:

[HttpPost]
public ActionResult Tflow(string json)
{  
    // deserialize
    var data = JsonConvert.DeserializeObject<JsonFileContentInputs>(json);

    // more code
}

型号:

// You can drop these two as we aren't using the modelbinding
// [ModelBinder(typeof(JsonModelBinder))] 
// [DataContract]
public class JsonFileContentInputs
{
    [JsonProperty(PropertyName = "baseDetails")]
    public Dictionary<string, string> BaseDetails { get; set; }  
}

不幸的是,在控制器中读取请求的原始流似乎是必要的,因为默认情况下 MVC 控制器不会很好地处理原始 JSON。 More info here.

编辑:看起来您可以将原始 JSON 传递给 MVC 控制器,您只需将 ajax 数据类型指定为 text 并确保参数名称匹配。我已经相应地更新了我的答案。

【讨论】:

    【解决方案2】:

    您应该将其作为字符串接收,然后将其序列化为如下所示的对象,而不是接收 Class 对象。

    public JsonResult Tflow(string basedetails)
    {   
        //some code
        var model = new JavascriptSerializer().Deserialize<JsonFileContentInputs>(basedetails);
        // Your code
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-10
      • 2016-05-28
      • 2012-01-25
      • 2016-07-05
      • 2017-06-22
      • 2012-10-03
      • 2015-08-02
      • 2013-07-03
      • 2012-11-26
      相关资源
      最近更新 更多