asp.net - jquery ajax post 转到 MVC 4 中的错误操作方法

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

这是我的观点

 <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 Controller 的方法:

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)。但是,由于我没有在索引中返回任何内容,因此我在警报框中收到 resp: undefined 。

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

最佳答案

您忘记了 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);
    }
});

关于asp.net - jquery ajax post 转到 MVC 4 中的错误操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17325892/

相关文章:

c# - 找不到资源(url)时,Web API 2.2 返回自定义 404

javascript - 包含具有各种显示标签的子元素的父 div 的淡入

jquery - 检查元素是否不存在并附加它

asp.net - 如何在server 2008上添加ASPNET帐户?

c# - 是否有一个开关可以将 SQL Server 表的字段的默认值作为 FormView/DetailsView 的 TextBoxes 的默认值?

javascript - 如何在数据添加到数据库后立即将数据发送到网页

asp.net-mvc - ASP.NET MVC 4 引用单父实体的多个外键

javascript - 将动态 Javascript 变量传递给 Django/Python

c# - 创建带有启用/禁用按钮的登录表单

c# - 具有 CMS 功能的 ASP.NET MVC3 应用程序