简体   繁体   中英

Refresh Session variable after a update in MVC4

I have code in the global.asax file:

if (user != null) HttpContext.Current.Session.Add("UserRole", user.Role.Trim());

There is a admin function where the role can be changed. The views keep on showing the old session value, ie the value set at the start of the session. How do I refresh the value?

: maybe I should be asking if theres a better way to do it? :也许我应该问是否有更好的方法来做到这一点? I use it in the views to show / hide menus and divs.

I have the following code in the _layout.cshtml file: $(document).ready(function () { if ('@(Session["UserRole"] == null)' == 'True') { //dp some stuff }

For clarity, here is the controller code: [HttpPost] public ActionResult Edit(int userid, string firstname, string lastname, string domain, string email, string role, string branch) { try { User user = context.Users.Find(userid); user.FirstName = firstname; user.LastName = lastname; user.DomainName = domain; user.Email = email; user.Role = role; user.Branch = branch; context.SaveChanges(); return RedirectToAction("ManageUsers"); } catch (Exception ex) {
} }
[HttpPost] public ActionResult Edit(int userid, string firstname, string lastname, string domain, string email, string role, string branch) { try { User user = context.Users.Find(userid); user.FirstName = firstname; user.LastName = lastname; user.DomainName = domain; user.Email = email; user.Role = role; user.Branch = branch; context.SaveChanges(); return RedirectToAction("ManageUsers"); } catch (Exception ex) {
} }

C# is server side code it is executed at page load so it will have the old value in it you have to get Session value from Server via ajax call:

$(document).ready(function () {


$.ajax({

url: '@Url.Action("GetSession","Home")',
success:function(response)
{

if (response === "") 
{ 
//dp some stuff 

}


}

});

}

and in action:

public ActionResult GetSession()
{
var SeesionValue = Session["UserRole"] !=null ? Session["UserRole"].ToString() : "";
return Content(SeesionValue );
}

I figured it out. I am using a global action filter. The filter is registered and then applied to all actions that requires it in the controller. public class ShowUserdetailsActionFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); using (Entities context = new Entities()) { var userName = filterContext.HttpContext.User.Identity.Name; var u = context.Users.Where(x => x.DomainName == userName).FirstOrDefault();

  filterContext.Controller.TempData.Add("UserRole", user.Role); } 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM