jquery - 提交 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,我是否可以获取表单中的变量并将其提交给我的控制器,以便在表单提交时页面不会重新加载?
目前它会回发并重新加载页面,在这种情况下我试图避免这种情况。
解决方案
您可以通过使用 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);
}
推荐阅读
- sql - 如何在 select 语句中包含 PERCENTILE_CONT 列,而不会生成有关 ORDER BY 子句或聚合函数的错误?
- node.js - NodeJS,使用 Multer 上传多张照片,但最后一张照片覆盖了所有其他照片
- php - 样式表未链接
- css - CSS 范围仅适用于 Angular 中的整个模块
- c# - 如何在 Microsoft bot v4 中从英雄卡中捕获用户回复
- swift - iOS 13 上的 ApplePay 错误“连接到远程警报查看服务失败”
- html - “如何在 HTML 和 CSS 中修复‘css 编辑后按钮不移动’”
- css - 如何使网格区域始终为页面的 100% 宽度?
- python - 使用 Python 在 Azure SQL 上启用 TDE
- hive - 在 Oracle 中是否有与转储函数等效的 Hive?