jquery - 使用 Ajax 调用将模型发布到控制器并返回单个变量以在屏幕上显示成功消息
问题描述
我可以通过 ajax 调用将模型传递给我的控制器,但我没有得到想要的结果。
控制器:
public async Task<ActionResult> UpdateUserDetails([Bind(Exclude = "Password, ReportPassword")]AdminViewModel model)
{
(.... Code that does not need to be displayed ....)
return Json(new { status = "success"}, JsonRequestBehavior.AllowGet);
}
阿贾克斯调用:
$("#submitUserDetails").submit(function (e) {
var userId = $("#Id").val();
var FirstName = $("#FirstName").val();
var LastName = $("#LastName").val();
var ResetUserPassword = $("#ResetUserPassword").val();
var Email = $("#Email").val();
var selectedRole = $("input:radio[name='RolesSelectedOnView']:checked").val();
var Model =
{
"Id": userId,
"FirstName": FirstName,
"LastName": LastName,
"ResetUserPassword": ResetUserPassword,
"Email": Email,
"rolesSelectedOnView": selectedRole
};
$.ajax({
url: '@Url.Action("UpdateUserDetails", "Admin")',
data: JSON.stringify(Model),
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status === "success") {
$.smallBox({
title: "<strong>Challenge Deleted</strong>",
content: "<i class='fa fa-clock-o'></i> <i>Challenge was successfully deleted! <strong>You will now be redirected back to the My Challenges page</strong></i>",
color: "#659265",
iconSmall: "fa fa-check fa-2x fadeInRight animated",
timeout: 4000
});
}
}
});
});
所以我想要的是同一个屏幕保持打开状态,但只希望“SmallBox”显示消息,而不是我得到一个空白屏幕:
{“状态”:“成功”}
该 URL 还包含模型中的所有信息,我也不想要。
我什至尝试了以下方法将表单发布到控制器(这也有效),但我得到了完全相同的结果!
$("#submitUserDetails").submit(function (e) {
var form = $(this);
var url = form.attr("UpdateUserDetails", "Admin");
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(form.serialize()), // serializes the form's elements.
dataType: "json",
contentType: "application/json; charset-utf-8",
success: function (data) {
//alert(data); // show response from the php script.
$.smallBox({
title: "<strong>User Details Saved</strong>",
content: "<i class='fa fa-clock-o'></i> <i> <strong></strong></i>",
color: "#659265",
iconSmall: "fa fa-check fa-2x fadeInRight animated",
timeout: 4000
});
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
我要做的就是提交数据,让控制器做它必须做的,然后弹出一条消息,它已成功保存。我究竟做错了什么 ?
编辑
值得一提的事情可能会有所帮助-这是从局部视图中运行的
解决方案
如果您使用 type="submit" 的按钮,我认为您需要return false
在事件处理程序中防止正常行为。
编辑:(基于聊天)
事件处理程序没有绑定到按钮,因为包含按钮的局部视图是在初始页面加载后呈现的。解决方案是将事件处理程序代码移动到局部视图中。
推荐阅读
- angular - 查询参数 Angular 5 路由错误
- arrays - ValueError:使用序列设置数组元素以将 word2vec 模型合并到我的 pandas 数据框中
- c# - 基于其他值的动态列值,例如在 Excel 中
- c# - MongoDB UpdateOne 没有更新记录
- xamarin - Xamarin Forms Media Plugin - 拍照返回屏幕弹出到根目录
- algorithm - 分析递归算法
- java - Java Hibernate 无效映射异常
- amazon-web-services - cloud-init cc_mounts.py 忽略 AWS EFS 挂载
- vba - Excel 错误 1004 用于特殊粘贴
- php - Twig 2 数组和 For 循环