views:

29

answers:

1

I'm was trying to fill in a description field when a drop-down was selected. I Got it working but I couldn't use a Json Content Type. This works

<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>

But when I uncomment the contentType: I get null returned to my controller. I've also tried

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

This is my controller

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

Why is it that when I have a contentType I get null passed? And what is the best way to encode Json data? I'm totally new at this and I couldn't find a straight forward explanation.

A: 
$.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);
      }
});

One of the gotchas with this function is that specifying a JSON contentType does not actually cause jQuery to JSON-encode your request. You have to do so manually or it will be serialized to application/x-www-form-urlencoded.

You need json2 and/or native JSON.

Matthew Flaschen
Thanks for the response but, I tired what you gave me and I still can't get Null in the controller. The post has {"ID":"string"} but it still shows null on the server side.
Peter