How to get the cookie in javascript in cshtml page

2019-08-31 03:12发布

问题:

I have created the cookie having user login id when user logs out and want to get that user login id in login page to populate the login id text box.

But I am not getting the cookie value in login page javascript function.

My logout action in homecontroller is like this:

public ActionResult Logout()
{  
    string loginId = SessionManager.UserloginId;      
    FormsAuthentication.SignOut();  
    Session.clear();  
    Session.Abandon();  
    HttpCookie cookie = new HttpCookie("UserLoginId");  
    cookie.value = loginId;  
    Response.Cookies.Add(cookie);
    return RedirectToActionPermanent("Index");  
}

And in Index.cshtml page my javascript code is like this:

<script type="text/javascript">
 var jcookie = '@Request.Cookies["UserLoginId"].Value';   
$("#LogInId").val() = jcookie;
</script>

But I am not getting the loginId stored in the cookie, please help me with this..

回答1:

If you need to set value using jQuery use .val(value) instead of $("#LogInId").val() = jcookie;. So change your code as

<script type="text/javascript">
    var jcookie = '@HttpContext.Current.Request.Cookies["UserLoginId"].Value';   
    $("#LogInId").val(jcookie);
</script>

Also, use @HttpContext.Current.Request instead of @Request

EDIT: As per comment

can u please tell me now how to set the value of this UserLoginId value to = ""(I mean blank) after i assign value to $("#LogInId").val(jcookie);?

If you want to set UserLoginId cookie value to blank, why are you saving it in cookie. You can easliy do this using TempData like

In controller

public ActionResult Logout()
{  
    string loginId = SessionManager.UserloginId;      
    FormsAuthentication.SignOut();  
    Session.clear();  
    Session.Abandon();  

    //Used here
    TempData["UserLoginId"] = loginId;  

    return RedirectToActionPermanent("Index");  
}

In Script

<script type="text/javascript">
    var jcookie = '@TempData["UserLoginId"]';   
    $("#LogInId").val(jcookie);
</script>

TempData value will be cleared after use



回答2:

try this:-

<Script type="test/javascript">
 var jcookie = '@Request.Cookies["UserLoginId"].Value';   
$("#loginId").val(jcookie)
</Script>