Reputation: 884
I have a situation where I need to generate an ID in javascript and put it into the masterpage somehow so that every time a request gets back to a controller I can get that value in the controller. I need this to work whether the request be from a form submit, or ajax call etc. In the controller I will have a property with a getter that pulls that value out of the masterpage somehow. Is this possible and how would it be achieved?
Upvotes: 0
Views: 47
Reputation: 169
Use cookie in client and get you can get value from controller.
Write a base controller and extends that controller in your controller.
Write method in base controller to read cookie and store a variable. you can access the variable from derived controllers.
See below example:
public class BaseController : Controller
{
private string _id = null;
protected string ID
{
get
{
var cookie = Request.Cookies.Get("ID");
if (cookie != null)
{
_id = cookie.Value;
}
return _id;
}
}
}
public class HomeController : BaseController
{
public ActionResult Index()
{
var test = ID;
ViewBag.Title = "Home Page";
return View();
}
}
// Place below code in your master page...
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
setCookie("ID", "123456", 1);
</script>
Upvotes: 1