0

I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller?

controller:

 [HttpPost]
    public JsonResult save(string inputdata)
    {
        return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet);
    }

view:

<button id="but">go</button>
<div id=result></div>
<script type="text/javascript">

    $(document).ready(

    $("#but").click(
        function () {
            $.ajax({
                url: "/Home/save",
                dataType: "json",
                type: 'POST',
                data: "test",
                success: function (result) {
                    $("#result").html(result.Result);
                }
            });

        }
    )

    );

</script>

1 Answer 1

3

You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request:

$.ajax({
    url: '/Home/save',
    dataType: 'json',
    type: 'POST',
    data: { inputdata: 'test' },
    success: function (result) {
        $('#result').html(result.Result);
    }
});

Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name:

$.ajax({
    url: '@Url.Action("save", "home")',
    dataType: 'json',
    type: 'POST',
    data: { inputdata: 'test' },
    success: function (result) {
        $('#result').html(result.Result);
    }
});

Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects.

Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server.

So the final version should look something along the lines of:

<script type="text/javascript">
    $(function() {
        $('#but').click(function () {
            $.ajax({
                url: '@Url.Action("save", "home")',
                type: 'POST',
                data: { inputdata: 'test' },
                success: function (result) {
                    $('#result').html(result.Result);
                }
            });
            return false;
        });
    });
</script>
Sign up to request clarification or add additional context in comments.

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.