首页 > 解决方案 > 提交 MVC 表单时抓取表单值以避免页面重新加载

问题描述

我有一个看起来像这样的 ASP.NET 剃须刀表单:

@using (Html.BeginForm("CreateUser", "Users", FormMethod.Post, new { role = "form", id="create-user-form" }))
{

@Html.LabelFor(model => model.LastName)
                            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

}

Then in my controller:

public ActionResult CreateUser(UserViewModel viewModel)
{



}

使用 jQuery,我是否可以获取表单中的变量并将其提交给我的控制器,以便在表单提交时页面不会重新加载?

目前它会回发并重新加载页面,在这种情况下我试图避免这种情况。

标签: jqueryasp.net-mvc

解决方案


您可以通过使用 Ajax 函数来做到这一点。如果这样做,您可以@using完全删除该块。

首先,在视图中添加一个按钮并给它一个 id。还要给你的输入字段一个id。

@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @id = "lastName" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
<button type="button" class="btn btn-success" id="createButton">Add user</button>

然后在代码底部添加一个脚本。以下假设您的 _Layout.cshtml 文件中有此代码:@RenderSection("scripts", required: false) 如果没有,请不要将脚本标签包装在这段代码中:@section Scripts {}

@section Scripts {
<script>
        // listen for button click event
        $('#createButton').click(function (e) {
            e.preventDefault();

            let lastName = $('#lastName').val();

            // Check for empty input -> exit if empty
            if ($.trim(lastName) == "") {
                return;
            }

            let data = JSON.stringify({
                lastName: lastName
            });

            // call saveUser ajax function, pass in data
            $.when(saveUser(data)).then(function (response) {
                alert(response);
            }).fail(function (err) {
                console.log(err);
            });
        });

        // Pass all data to Controller for saving
        function saveUser(data) {
            return $.ajax({
                url: '/Users/CreateUser',
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                processData: false,
                cache: false,
                data: data,
                success: function (result) {
                    console.log(result);
                },
                error: function () {
                    alert('Error! Please contact an administrator if the problem persists.')
                }
            });
        }
    </script>
}

最后,设置您的控制器操作,如下所示:

[HttpPost]
public JsonResult CreateUser(string lastName)
{
    // prepare a return statement
    string result = "Error! Please contact an administrator if the problem persists.";

    // perform your create logic here, then check if it succeeded or not


    if (createSucceeded == true)
    {
        // change result string to a success message
        result = "Success! User created!";
    }

    // Return the result string
    return Json(result, JsonRequestBehavior.AllowGet);
}

推荐阅读