Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the username after login

I have to learn C# MVC using LINQ. Now I don't know how to send the username after login

How to send the username from the database to view?

public ActionResult Login(Login log)
{
    using (var dbs = new guruEntities())
    {
        var check = dbs.Logins.FirstOrDefault(x => x.Name == log.Name && x.Password == log.Password);
        if (check != null)
        {
            return RedirectToAction("Success");
        }
        else
        {
            ViewBag.msg = "Wrong data";
        }
    }
    return View("Login");
}

public ActionResult Success(Login log)
{
    using (var dbs = new guruEntities())
    {
        var check = dbs.Logins.FirstOrDefault(x => x.Name == log.Name && x.Password == log.Password);

        return View();
    }
}

View:

<div> 
    Welcome <!--How do I display the Username here? -->
</div>
like image 435
Guru Rahaventhar N Avatar asked Oct 14 '25 03:10

Guru Rahaventhar N


1 Answers

Because you use redirect so need use TempData to keep your username like this.

 public ActionResult Login(Login log)
    {
        using (var dbs = new guruEntities())
        {
            var check = dbs.Logins.FirstOrDefault(x => x.Name == log.Name && x.Password == log.Password);
            if (check != null)
            {
                TempData["UserName"] = check.Name;
                return RedirectToAction("Success");
            }
            else
            {
                ViewBag.msg = "Wrong data";
            }
        }
        return View("Login");
    }

In your view

<div> 
    Welcome @TempData["UserName"]
</div>
like image 197
Hien Nguyen Avatar answered Oct 19 '25 12:10

Hien Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!