Asp.net Mvc html表单发布到错误的控制器操作

我有一个具有2个动作的控制器:


public class OrganizationUnitsController : Controller

{

    public ActionResult Create()

    {

        // return empty form

        return View();

    }


    [HttpPost]

    public ActionResult Save(OrganizationUnitViewModel unitViewModel)

    {

        // Save the new unit to the DB

        return View();

    }

}

该Create.cshtml是:


@using (Html.BeginForm("Save", "OrganizationUnits", FormMethod.Post, new { @id = "form", @class = "form-horizontal" }))

{


    <!-- Some inputs -->


    <a href="" class="btn btn-primary">Save</a>

}


$('#form')

.on('submit',function (e) {

        e.stopPropagation();


        $.ajax({

            url: '@Url.Action("Save", "OrganizationUnits")',

            type: "POST",

            dataType: "json",

            contentType: "application/json; charset=utf-8",

            data: JSON.stringify({

                      Name: $('#Name').val(),

                      Admin: JSON.stringify({ 'FullDescription': $('#Admin').val() }),

                      Members: JSON.stringify( $('#users_list_box').val() )

            });

});

问题是,当我单击保存按钮时,使unitViewModel并将表单传递给Save操作的javascript代码没有被调用,而Create操作被调用了。


将@ Html.BeginForm()中的控制器动作更改为null不能解决问题。


我该如何解决?


繁华开满天机
浏览 141回答 1
1回答

素胚勾勒不出你

Stephen Muecke的正确性<a href="" class="btn btn-primary">Save</a>是有问题的,单击它会导致出现GET,请尝试将其替换为submit输入类型。<input type="submit" class="btn btn-primary" value="Save" />并使用,e.preventDefault();因为这样可以stopPropagation阻止事件使事件链冒泡,而preventDefault阻止浏览器对该事件进行默认操作。$('#form').on('submit',function (e) {&nbsp; &nbsp; var actionUrl = this.action;&nbsp; &nbsp; e.stopPropagation();&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: actionUrl,&nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; contentType: "application/json; charset=utf-8",&nbsp; &nbsp; &nbsp; &nbsp; data: JSON.stringify({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name: $('#Name').val(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Admin: JSON.stringify({ 'FullDescription': $('#Admin').val() }),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Members: JSON.stringify( $('#users_list_box').val() )&nbsp; &nbsp; &nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP