简体   繁体   English

提交 MVC 表单时抓取表单值以避免页面重新加载

[英]Grab form values to avoid page reload when submitting a MVC form

I have a ASP.NET razor form that looks something like:我有一个 ASP.NET razor 表单,看起来像:

@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)
{



}

Using jQuery, is it possible for me to grab the variables in the form and submit it to my controller such that the page doesn't reload when the form submits?使用 jQuery,我是否可以获取表单中的变量并将其提交给我的控制器,以便在表单提交时页面不会重新加载?

Currently it does a post back and the page reloads, which I am trying to avoid in this situation.目前它会回发并重新加载页面,在这种情况下我试图避免这种情况。

You can either set up an AJAX call in jQuery, or you can utilize the jQuery Unobtrusive Ajax Nuget Package (I am more familiar with setting up this).您可以在 jQuery 中设置 AJAX 调用,也可以使用 jQuery Unobtrusive Ajax Nuget Package(我更熟悉设置)。

Using this package, you can take advantage of the Ajax submitform helper attribute.使用这个包,您可以利用 Ajax submitform 帮助程序属性。

The main purpose of this is to have one div section (encapsulated within the AJAX form element) that contains the input fields that are submitted.这样做的主要目的是让一个 div 部分(封装在 AJAX 表单元素中)包含提交的输入字段。 Then, when submitted, it calls a Partial View Result (that requires a return PartialView(); ) and displays it in your original parent view, without reloading the page.然后,在提交时,它调用 Partial View Result(需要 return PartialView(); )并将其显示在原始父视图中,而无需重新加载页面。

Here is an example setup:这是一个示例设置:

<div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4">
    @{using (Ajax.BeginForm("PartialViewResultName", "ControllerName", null, new AjaxOptions
      {
          HttpMethod = "GET",
          UpdateTargetId = "targetDivID",
          InsertionMode = InsertionMode.Replace,
          LoadingElementId = "targetDivLoadingID"
      }, new
      {
          id = "formID"
      }))
      {
          // Where your Html code that will be submitted goes
          <button type="submit">submit</button>
      }}
    </div>
    <div class="col-md-4"></div>
</div>
<div class="row">
    <div class="col-md-12">
        <div id="targetDivID"></div>
    </div>
</div>

You can do this by using an Ajax function.您可以通过使用 Ajax 函数来做到这一点。 If you do this, you can remove the @using block altogether.如果你这样做,你可以完全删除@using块。

First, add a button to your view and give it an id.首先,向您的视图添加一个按钮并为其指定一个 id。 also give your input field an 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>

Then add a script at the bottom of your code.然后在代码底部添加一个脚本。 The following assumes you have this code in your _Layout.cshtml file: @RenderSection("scripts", required: false) If not, don't wrap the script tags in this bit of code: @section Scripts {}以下假设您的 _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>
}

Finally, set up your controller action something like this:最后,像这样设置你的控制器动作:

[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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM