Reputation: 8373
How do you use JQuery/javascript to get the username on the client side of an ASP .NET MVC application and post it back to the server for the controller to process?
I would like the following sequence of events to occur:
Upvotes: 2
Views: 9328
Reputation: 21894
To add to the discussion here, we can get the username into a javascript variable as follows:
<text>var jsUser = '@HttpContext.Current.User.Identity.Name.ToString()';</text>
Upvotes: 0
Reputation: 2729
To build on top of @Jacob answer, get the value in server side controller populate a viewmodel property with this value of variable username
var username = HttpContext.Current.User.Identity.Name.ToString();
vmUser.UserName = username; // Here vmUser is a sample ViewModel
In cshtml, if using razor engine use a hidden variable by using one of the constructs below
@Html.Hidden or
@Html.HiddenFor(um=>um.UserName)
to access it in Jquery or JavaScript Hope this add on helps for newbies in mvc and jquery
Upvotes: 0
Reputation: 78920
On the client side of things, you shouldn't have access to the username. You don't need it, either. In your server-side code, you can access the Windows Authentication username with this code:
var username = HttpContext.Current.User.Identity.Name.ToString();
Upvotes: 3