1

I am using MVC session variable in Razor view javascript. But if I want set that session value to null how to do that?

 function UpdateMembershipJavascriptObject() {
        var tempMembership = @Html.Raw(JsonConvert.SerializeObject(Session["Membership"]));
        if (tempMembership) {

            membershipData.updateMembership(tempMembership);
            updateSubtotal();     
            //here I set to null
        }
    }

I tried '@Session["Membership"]' = null but getting error on = null on the browser.

2
  • Is session the correct choice? If you want to read back once in the same request and then have the session item removed you can use TempData instead which is cleared at the end of the request. Commented Jul 18, 2016 at 14:32
  • Using Session State directly is a bad practice in ASP.Net MVC. What kind of information do you want to store? Commented Jul 18, 2016 at 14:39

1 Answer 1

1

Session variables are a server side thing. Your javascript code executes on client side browser. So you cannot set a server side variable from your javascript code directly.

What you can do is, make an ajax call to a server action method and update the session value there.

if (tempMembership) {

        membershipData.updateMembership(tempMembership);
        updateSubtotal();     

        $.post("@Url.Action("SetSession","Home")",function(){
               //done. Do something else
        });
}

Assuming you have a SetSession action method in your HomeController

[HttpPost]
public ActionResult SetSession()
{
   Session["Membership"]=null;
   return Json(new { status="success"});
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.