Json contentType:将Jquery POST分解为MVC控制器

时间:2010-08-19 02:02:35

标签: .net json asp.net-mvc-2 jquery

我正在尝试在选择下拉列表时填写说明字段。我有它工作,但我不能使用Json内容类型。这工作

<script type="text/javascript">
    $(document).ready(function () {
        $("#ddl_id").change(function () {
            var test = $("#ddl_id").val();
            $.ajax({
                type: "POST",
                url: "<%= Url.Action("GetVal") %>",
                data: {id: test},
                //contentType: "text/plain",
                dataType: "json",
                success: function(result) {
                    $("#serial").val(result);
                },
                error: function(e) {
                    alert(e);
                }
            });
        });
    });

</script>

但是当我取消注释contentType时:我将null返回给我的控制器。我也试过了

contentType: "application/json; charset=utf-8",

这是我的控制器

 [HttpPost]
    public JsonResult GetVal(string id)
    {.......

为什么当我有一个contentType时,我会传递null?编码Json数据的最佳方法是什么?我对此完全陌生,我找不到直接的解释。

2 个答案:

答案 0 :(得分:2)

$.ajax({
      type: "POST",
      url: "<%= Url.Action("GetVal") %>",
      data: JSON.stringify({id: test}),
      contentType: "application/json",
      dataType: "json",
      success: function(result) {
          $("#serial").val(result);
      },
      error: function(e) {
          alert(e);
      }
});

使用此函数的其中一个问题是指定JSON contentType实际上并不会导致jQuery对您的请求进行JSON编码。您必须手动执行此操作,否则将序列化为application/x-www-form-urlencoded

您需要json2和/或原生JSON。

答案 1 :(得分:0)

在服务器端,使用对象获取参数值。 喜欢:

public class sealed MyClass{
   public Int32 ID{get;set;}
   // other properties here...
}

在动作方法中使用

[HttpPost]
public ActionResult MyAction(MyClass mycls){
    // here your can get the property,like
    mycls.ID;
}

你可以阅读MSDN博客: Introducing ASP.NET MVC 3 (Preview 1)