I'm trying to get the value entered into a textbox though jquery and pass this from my login-view to my index-view to show the username. I tried using the bellow but nothing gets displayed.
How can this be done ? and what is the recommended method?
Login :
<script>
$("#loginbutton").click(function () {
var username = ($("#username").val());
ViewBag.Usersname = username;
});
</script>
<body>
<form action="CheckUser" method="post" class="form-horizontal col-md-6 col-md-offset-4">
<h1>Welcome to the Report Login</h1><br />
<label class="control-label">Username or Email:</label><br />
<input type="text" class="form-control" name="username"> <br />
<label class="control-label">Password:</label><br />
<input type="password" class="form-control" name="password"> <br />
<input type="checkbox" name="remember" value="rememberme" /> Remember me <br />
<a href="@Url.Action("ForgotPassword", "Home")" class="elements"><span>Forgot Password?</span></a><br />
<div class="col-md-7 text-center">
<button type="submit" class="btn btn-success" id="loginbutton">Log In</button>
</div>
</form>
</body>
Index contains:
@ViewBag.Usersname
User.Identity.Namewherever you wantViewBag.Usersname = username;will not work. You need to keep in mind that you can use Razor to set client side variable when the page is generated but you cannot use JavaScript to set server side variables. UsingViewBagis the way to go (usually), but this needs to be set in the controller. After you correctly log in the user, set its name in theViewBag. Remember there's no two-way-binding, so whatever happens to your variable on the client side, will not be reflected on the server (unless you send the values using a HTTP request).