Seth
Seth

Reputation: 8373

Get username at the client with ASP.NET MVC

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:

  1. Get username of client machine.
  2. Post username back to server.
  3. Instantiate new object that takes the username in the constructor. (Using Ninject for DI)
  4. Inject the object into the receiving controller.

Upvotes: 2

Views: 9328

Answers (3)

vijayst
vijayst

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

Sundara Prabu
Sundara Prabu

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

Jacob
Jacob

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

Related Questions