One of the place I had to pass a value from a view to a partial view but I was not supposed to alter the model. Hence. I went back to the roots and used session to pass the value between the views. Whats important here is that, as it is a session value, you can pass it from anywhere to anywhere. It will always be accessible. So here’s how to do it:
The beauty of session is, you can use it from anywhere:
Part 1: Saving the Value
1. From Controller:
public class Yourontroller : Controller { public ActionResult SetSession(string value) { Session["YourSessionKey"] = value; return View(); } }
2. From View:
Snippet.cshtml
@model contracts.ModelName
@{
Session[“YourSessionKey“] = @Model.Name;
}
Part 2: Accessing the value:
You can again access this value in controller or view both.
In controller:
public class Yourontroller : Controller { public ActionResult GetSession(string value) { var SessionValue=Session["YourSessionKey"]; return View(); } }
In View:
Snippet
@model contracts.SomeOtherModel @{ int SessionValue = Session["YourSessionKey"];
}
There you go! Happy coding!