开发者

jquery Post does not work in asp.net mvc 3?

开发者 https://www.devze.com 2023-04-08 01:20 出处:网络
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?

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>


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

精彩评论

暂无评论...
验证码 换一张
取 消