我正在开发MVC应用程序, 在文本框Blur上,它正在调用jQuery函数,而后者又会调用控制器。
下面是jQuery代码
$(document).ready(function () {
$('#UserId').blur(function () {
//alert(1);
var userId = $("#UserId").val();
var url = '@Url.Action("IsValidUser", "UserRoleCompany")';
$.ajax({
url: url,
data: { userId: userId },
cache: false,
type: "POST",
success: function (data) {
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
下面是控制器代码,
public ActionResult IsValidUser(string userID)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
try
{
objLMT.UserList = objLMTDAL.IsValidUser(userID);
bool IsValidUser = objLMT.UserList.Any(cus => cus.UserId == userID);
if(!IsValidUser)
TempData["Msg"] = "Please enter valid User Id";
return RedirectToAction("Index", "UserRoleCompany");
}
catch (Exception ex)
{
//TempData["Msg"] = ex.Message;
//return Json(objLMT);
throw ex;
}
}
控制器工作正常,并被分配了如图所示的值
TempData [“ Msg”] =“请输入有效的用户ID”;
但是当调用$('#UserId')。blur(function()时,查看代码未显示通知消息。
@if (TempData["Msg"] != null)
{
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-
hidden="true">×</button>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
<a href="#" class="alert-link">Alert Link</a>.
</div>
}
它应该显示,
亲切的向导。
答案 0 :(得分:1)
在这种情况下,您不应使用temptdata。尝试返回正确的Json(成功或错误):
public ActionResult IsValidUser(string userID)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
try
{
objLMT.UserList = objLMTDAL.IsValidUser(userID);
bool IsValidUser = objLMT.UserList.Any(cus => cus.UserId == userID);
if (!IsValidUser) {
return Json(new { success = false, responseText = "Please enter valid User Id." }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = true, responseText= "UserRoleCompany/Index"}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { success = false, responseText = "Something went wrong..." }, JsonRequestBehavior.AllowGet);
}
}
然后只需使用jQuery检查以引导JS警报或将window.location设置为您返回的网址(或您的想法)。