Reputation: 101
I am working on MVC application, On textbox Blur it's calling jQuery function which in turn call controller.
Below is the jQuery code
$(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);
}
});
});
});
The controller code is below,
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;
}
}
The controller is working properly and get assigned with the value as shown
TempData["Msg"] = "Please enter valid User Id";
But view code is not showing the notification message when $('#UserId').blur(function () gets called.
@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>
}
It should show,
Kindly Guide.
Upvotes: 1
Views: 751
Reputation: 1742
You should not work with temptdata in this case. Try to return the right Json (success or error):
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);
}
}
Then just check with your jQuery to alert with bootstrap JS or set the window.location to the url you get back (or whatever your idea is).
Upvotes: 1