如何使用MVC3控制器显示“消息框”

在控制器中执行某些代码后,我一直面临着显示“消息框”的问题

对于前: –

public ActionResult IsLoginExsit(CustomerDO loginData) { JsonResult jsonResult = new JsonResult(); if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty(loginData.Password)) { bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password); jsonResult.Data = result; } return jsonResult; } 

如上例所示,如果result为true或false,那么我想显示一条消息框,说明登录是suceess还是失败。

  

如果登录存在,我想导航到“/ Customer / CollaborationPortal”,否则我想显示消息“Authroization fail”。

 $("#btnGo").click(function (e) { var RegData = getRegData(); if (RegData === null) { console.log("Specify Data!"); return; } var json = JSON.stringify(RegData) $.ajax({ url: '/Registration/IsLoginExsit', type: 'POST', dataType: 'json', data: json, contentType: 'application/json; charset=utf-8', success: function (data) { if(data.result == true){ location.href = "/Customer/CollaborationPortal"; } else{ alert("Login failed"); //or whatever } } }); return false; }); function getRegData() { var UserName = $("#txtUserName").val(); var Password = $("#txtPassword").val(); return { "UserName": UserName, "Password": Password }; } 

提前致谢

在MVC中没有办法像winforms应用程序那样简单。

在您的案例中,在网页上显示消息框的最简单方法是将此操作从ActionResult更改为JsonResult,并将if替换为:

 return Json(new {result = result}); 

并且,在网页中你需要使用ajax(即使用jquery的$ .post提交表单)并在回调函数中检查结果:

 $("form input[type=submit]").click(function(){ var formData = $(this).closest("form").serialize(); $.post("urltoyourcontrollerhere/IsLoginExsit", formData, function(data){ if(data && data.result == true){ alert("Login exists!");} }); }); 

更新您发布的代码似乎没问题,但有一个问题。 成功function:

 success: function (data) { location.href = "/Customer/CollaborationPortal"; } 

无论返回什么控制器,此函数将始终执行重定向。 您需要检查data.result(如果您将json作为Json返回(new {result = result});)为true,然后重定向,否则显示alert。 所以,试试:

 success: function (data) { if(data.result == true){ location.href = "/Customer/CollaborationPortal"; } else{ alert("Login failed"); //or whatever } } 

另一件事:

  var RegData = getRegData(); if (RegData === null) 

如果您希望这样做,则当其中一个文本框为空时,您需要从getRegData返回null。

完成后,您可以显示消息框。

 public ActionResult LoginExist(BAMasterCustomerDO loginData) { return new JavascriptResult { Script = "alert('Saved successfully');" }; } 

您将无法使用服务器端代码显示消息框。 您需要将一些数据传递回指示登录状态的视图,然后编写一些客户端代码以显示消息框。

您可以使用视图模型的属性,该属性将传递给视图,其中包含以下信息:

 var model = new MyViewModel(); bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password); model.IsLoginSuccess = result; ... return View(model); 

在强类型视图中,您将测试此属性的值并相应地显示消息:

 @if (Model.IsLoginSuccess) { 
The Login was successful
}