3

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
3
  • Are you using the provided login api? If so, you can just use User.Identity.Name wherever you want Commented Sep 10, 2014 at 9:46
  • Hi Andrei, no afraid I'm using my own solution to learn more of mvc. :) Commented Sep 10, 2014 at 10:10
  • Well then, first of all, this line ViewBag.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. Using ViewBag is 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 the ViewBag. 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). Commented Sep 10, 2014 at 10:23

2 Answers 2

1

Login view:-example

<script>

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function SetCookieFromModel() {
       user = @ViewBag.Usersname
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
}

</script>

Index View:-

<script>
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
function GetCookieFromModel() {
var user=getCookie("username");
}
</script>

2nd way in MVC using TempData here I have done a simple example. Here I am getting employee Id on second view. Simulate your example according to this

Model:

  public class Information
    {

        public string EmpId { get; set; }

    }

Controller:

public class EmpController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }    
        [HttpPost]
        public ActionResult Index(Information ifn ,string info)
        {

            var getInfo = ifn.EmpId;
            TempData["EmployeeInformation"] = getInfo;

            return RedirectToAction("ShowEmployee");
        }           
        public ActionResult ShowEmployee()
        {
            return View();            
        }
    }

View for Index:

  <div>
      @using (Html.BeginForm()) {
              @Html.LabelFor(m => m.EmpId)
                @Html.TextBoxFor(m => m.EmpId)             
      }
    </div>

2nd View for ShowEmployee:

 <div>
     your info : @TempData["EmployeeInformation"]

    </div>
Sign up to request clarification or add additional context in comments.

Comments

0

there is a simple solution all you have to do is set a cookie and read it from controller

(function () {
    var onLoginClick = function() {
        var userName = $('txtUserName').val();
        $.ajax({
            url: '@Url.Content("~/Login")',
            dataType: 'json',
            async: false,
            data: {
                userName: userName
            }
        });
    }
}())

On your Login Controller Action need to set the cookie

HttpCookie loginCookie = new HttpCookie("loginCookie"); 
Response.Cookies["loginCookie"].Value = userName; 
Response.Cookies.Add(loginCookie);

then on Index Action on any controller you can check the cookie and set it.

HttpCookie cookieUser= Request.Cookies["loginCookie"];
ViewBag.Username = Server.HtmlEncode(cookieUser.Value);

2 Comments

Hi Gayan thank-you for your response, Ive added your code into my project. The JQuery in my Login.cshtml, cookie part in public ActionResult Login() and the final part in public ActionResult Index with a corresponding viewbag.username in my index.cshtml page. The only issue I have is where ["loginCookie"].Value = userName; username doesn't exist in the current context. Have I missed something ????
yeah you have to get it as a parameter of the action like public ActionResult Login(string userName){}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.