0

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.

0

2 Answers 2

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);
      }
});

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

On the server side, use an object to get the parameters value. like :

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

in the action method use like

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

you can read read the MSDN blog: Introducing ASP.NET MVC 3 (Preview 1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.