-1

I am trying to get session value in mvc5 razor as below

@{var cnt=Session["count"].ToString();}
@if (cnt == "0" || string.IsNullOrWhiteSpace(cnt))

This results in an error if there is no value for session. How should this be checked

Diin
  • 551
  • 7
  • 37
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeCaster Feb 28 '17 at 10:55
  • I'd really avoid checking session variables in your view – ediblecode Feb 28 '17 at 11:05
  • how do you do it when you have to show an alternative html or view if session is null in a shopping cart? – Diin Feb 28 '17 at 11:16

1 Answers1

3

Simply check if its null

@if (Session["count"] != null) { 
    //Do what you want 
}
Muhammad Saqlain
  • 1,934
  • 4
  • 29
  • 41