我想在控制器中发生错误时将partialview显示为jQuery模式。提交表单后,我需要检查验证,如果验证失败,则在jQuery模型弹出窗口中显示部分视图。
<div class="form-actions">
<button type="submit" class="btn btn-primary" >Save changes</button>
@Html.ActionLink("Cancel", "Index", new {id=Model.Contact.Number}, new { @class = "btn " })
</div>
MemberController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Activity activity)
{
try
{
byte[] committeeMemberSpeId = Convert.FromBase64String(activity.Id);
var committeeMember = db.Committee_Member.FirstOrDefault(x => x.Committee_Member_Id == committeeMemberId);
if (ValidateEndDate(activity)) //Show here PartialView("ErrorDetail");
if (ModelState.IsValid)
{
if (committeeMember != null)
{
....
....
db.Entry(committeeMember).State = EntityState.Modified;
db.SaveChanges();
Success("Your information was saved!");
return RedirectToAction("Index", new { id = committeeMember.Customer_Number });
}
}
ViewBag.Roles = TempData["Roles"];
TempData["Roles"] = TempData["Roles"];
return View(activity);
}
catch (Exception exception)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
PartialView("ErrorDetail");
}
}
我们怎么能这样做?
答案 0 :(得分:2)
您可以使用Ajax请求发布帖子并将Json从操作返回到视图,然后在jquery Ajax调用的回调中显示对话框中的错误:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Activity activity)
{
//Do stuff
return Json(flag, JsonRequestBehavior.AllowGet);
}
flag
只是一个简单的类,它具有Error和Success字符串/布尔值,用于向用户显示结果。
public class Flag
{
public bool Success { get; set; }//determine whether the call succeeded or not
public string Error { get; set; }//show some detailed error message
}
然后在您的视图中显示以下ajax请求:
function serializeAndSendLoginForm() {
var form = $("#logOnForm").serialize();
$.ajax({
url: '<%: Url.Action("LogOn","Account",new{area="Security"}) %>',
type: 'POST',
data: form,
success: function (data) {
if (data.Success) {
//do more stuff
} else {
showDialog(data.Error);
}
},
error: function () {
alert("error");
}
});
}
加载对话框的功能:
function showDialog(message){
var $dialog = $('<div></div>')
.html(message)
.dialog({
autoOpen: false,
modal: true,
height: 625,
width: 500,
title: "Login Result"
});
$dialog.dialog('open');
}
您可以使用某个容器类(而不是我的答案中的标志变量)从控制器向视图返回其他信息,并向用户显示其他错误详细信息。