【问题标题】:jquery ajax post goes to the wrong action method in MVC 4jquery ajax post 转到 MVC 4 中的错误操作方法
【发布时间】:2013-06-26 16:44:33
【问题描述】:

这是我的看法

 <div>
    @using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post, new { id="FormPost" }))
    { 
    @Html.TextBoxFor(x=> x.Name)<br />
    @Html.TextBoxFor(x => x.LastName)<br />
    @Html.TextBoxFor(x => x.Age)
    <input type=submit value="submit" />
    }
</div>

<script>

    $(document).ready(function () {
        $('#FormPost').submit(function (e) {
            //This line will prevent the form from submitting
            e.preventDefault();
            alert('ajax post here');

            $.ajax({
                type: 'POST',
                url: $('FormPost').attr('action'),
                data: $('FormPost').serialize(),
                accept: 'application/json',
                error: function (xhr, status, error) {
                    alert('error: ' + xhr.statusText);
                },
                success: function (response) {
                    alert('resp: ' + response.data);
                }
            });
        });


    });

 </script>

这些是 Home 控制器的方法:

public ActionResult Index()
{
    return View();
}


[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
    IndexVM _vm = vm;
    return Json("name posted was: " + _vm.Name);

}

这是路线图

 routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

当页面加载时,它会转到 Index 操作方法,这是可以理解的。但是,当我提交表单时,它会再次进入 Index 操作方法。这是为什么呢?

显示警报消息“ajax post here”,然后显示成功警报(“resp:”+ response.data)。但是,由于我没有在索引中返回任何内容,因此我在警报框中得到了一个响应:未定义。

如何解决此问题,以便表单发布到 public JsonResult jQueryPost(IndexVM vm) 方法?我还尝试将 JsonResult 替换为 ActionResult 并且效果相同。

【问题讨论】:

    标签: asp.net asp.net-mvc jquery asp.net-mvc-4


    【解决方案1】:

    你忘记了 jQuery 选择器中的 #

    $.ajax({
        type: 'POST',
        url: $('#FormPost').attr('action'),
        data: $('#FormPost').serialize(),
        accept: 'application/json',
        error: function (xhr, status, error) {
            alert('error: ' + xhr.statusText);
        },
        success: function (response) {
            alert('resp: ' + response.data);
        }
    });
    

    【讨论】:

    • 谢谢。那行得通。我不能再接受5分钟的答案。很快就会这样做。
    • 谢谢,很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多