【发布时间】:2019-07-24 05:51:14
【问题描述】:
这里我EditMyProfile 方法用于编辑客户详细信息。
在这种方法中,我尝试设置ViewBag.msg = 1 并返回return PartialView("MyProfile", getCusomerDetail);,设置ViewBag.msg = 0; 并返回return PartialView("EditMyProfile", customer); 并使用该ViewBag.msg 值希望在AJAX 成功上放置条件是否显示成功消息。
现在,问题是即使ViewBag.msg 在EditMyProfile 视图中具有价值,var message = '@ViewBag.msg' 在 AJAX 成功中也会提供var message = ""。
对我的代码的任何帮助都将是一个很大的帮助
谢谢
下面是我的 AJAX
<script>
$(document).ready(function () {
$("#EditMyProfileCreate").submit(function (ev) {
debugger;
ev.stopImmediatePropagation();
var Action = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: Action,
type: 'POST',
data: formData,
async: false,
success: function (data) {
debugger
var message = '@ViewBag.msg'; // Here the var message = "" even though @ViewBag.msg' has value
if (message == "1") {
swal("Congratulations!", "Chages saved successfully", "success");
$("section#myAccountMainDiv").html(data);
}
else {
$("section#myAccountMainDiv").html(data);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
})
下面是我的
[HttpPost]
public ActionResult EditMyProfile(CustomerVM customer)
{
if (ModelState.IsValid)
{
using (emedicineEntities _db = new emedicineEntities())
{
var getCustomer = _db.Customers.Where(x => x.CustomerId == customer.CustomerId).FirstOrDefault();
getCustomer.CustomerName = customer.CustomerName;
getCustomer.CustomerPhoneNumber = customer.CustomerPhoneNumber;
getCustomer.CustomerEmail = customer.CustomerEmail;
getCustomer.CustomerAddress = customer.CustomerAddress;
getCustomer.ConfirmPassword = getCustomer.PasswordHash;
_db.Entry(getCustomer).State = EntityState.Modified;
_db.SaveChanges();
ViewBag.msg = 1; // here ViewBag.msg is set 1 on successfull edit
var getId = Global.CustomerId;
var getCusomerDetail = _db.Customers.Where(x => x.CustomerId == getId).FirstOrDefault();
return PartialView("MyProfile", getCusomerDetail);
}
}
else
{
ViewBag.msg = 0; // here ViewBag.msg is set 0 when model is invalid
return PartialView("EditMyProfile", customer);
}
}
【问题讨论】:
-
如果我说一旦视图被渲染,模型对象就不存在了,我错了吗?关于 Razor 视图引擎的这一点对我来说仍然有点困惑
标签: c# jquery ajax asp.net-mvc-5