0

I'm trying to assign a session value to a Model Property in Razor view like following

@Html.HiddenFor(model => model.Image, new { @Value = Session["PICTURE"].ToString() })

But this is not working properly , getting following error when session is null

Object reference not set to an instance of an object.

kez
  • 2,087
  • 6
  • 46
  • 103
  • Try `Session["PICTURE"] as string` instead. I think your session may be `null`, when `null` use `.ToString()` you will get that's exception. –  Oct 28 '16 at 06:25
  • Never set the `value` attribute when using a `HtmlHelper` method. You assign the value to the `Image` property of the model before you pass it to the view. –  Oct 28 '16 at 06:26
  • @TooNDinDarkDevil but how to extract that session value as string then ? – kez Oct 28 '16 at 06:26
  • @StephenMuecke so How can I do this ? whats you suggesting ? – kez Oct 28 '16 at 06:27
  • In your `GET` method, you assign the value, but you also need to check if its not `null` first. –  Oct 28 '16 at 06:29
  • @kez `string stringValue = Session["PICTURE"] as string` you can code like this. :) –  Oct 28 '16 at 06:29
  • @kez If you don't sure the session is declare, you can check it before getting session value by `string stringValue = (Session == null ? (string)null : Session["PICTURE"] as string);`. Let try ! :) –  Oct 28 '16 at 06:33
  • The error message seems come from NRE (NullReferenceException), it may fit as duplicate to http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it. – Tetsuya Yamamoto Oct 28 '16 at 10:17

0 Answers0