FahadAzeem
FahadAzeem

Reputation: 127

ViewBag is not sending any value to the view

In ASP.NET Core MVC, I'm facing trouble creating a login panel, I'm using sessions after the user is logged into the account and I'm storing the session values inside the ViewBag. But the ViewBag does not get any value inside of it, it rather gets null value inside it.

Here's the controller

[HttpPost]
        public IActionResult Login(userModel model)
        {
            var findValue = _context.users.Any(o => o.username == model.username);
            var findValue2 = _context.users.Any(o => o.password == model.password);
            if (findValue && findValue2)
            {
                HttpContext.Session.SetString("Username", model.username);
            }
            return View(model);
        }

public IActionResult Index()
        {
            ViewBag.Username = HttpContext.Session.GetString("Username");
            return View();
        }

And here's the view Index.cshtml

@model ComplaintManagement.Models.userModel
@{
    ViewData["Title"] = "Portal";
}

<h1>Welcome @ViewBag.Username</h1>

Login.cshtml

@model ComplaintManagement.Models.userModel
@{
    ViewData["Title"] = "Login";
}
<div class="row mb-3">
    <div class="col-lg-4"></div>

    <div class="col-lg-4 border login" style="background-color: #d3d1d1;">
        <h4 class="mt-3 text-center">
            <i class="fa fa-lg fa-user text-secondary"></i><br />
            Login
        </h4>
        <hr />
        <form method="post" asp-action="Index" asp-controller="Portal">
            <div class="text-danger"></div>
            <div class="text-warning">@ViewBag.Name</div>
            <div class="form-group">
                <label class="mt-4 asp-for=" username"">Username</label>
                <input class="form-control" type="text" required="required" asp-for="username" />
                <span></span>
            </div>

            <div class="form-group">
                <label class="mt-4" asp-for="password">Password</label>
                <input type="password" class="form-control" required="required" asp-for="password" />
                <span></span>
            </div>

            <center>Don't have an account? <a asp-controller="Portal" asp-action="Register">Register here</a>.</center>
            <center><button value="login" class="btn btn-primary mt-3 w-25 mb-3 align-content-center">Login</button></center>
        </form>
    </div>
    <div class="col-lg-4"></div>
</div>

Upvotes: 2

Views: 1140

Answers (1)

Michael Wang
Michael Wang

Reputation: 4022

Session and state management in ASP.NET Core

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1


Here is a demo How to use Session in ASP.NET Core.

1. Codes of Startup Configurations

AddSession in ConfigureServices, UseSession in Configure.

 public class Startup
 {

    public void ConfigureServices(IServiceCollection services)
     {
        ...
        services.AddSession();
        ...
     }
     
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseSession();

        app.UseStaticFiles();

        ....
    }

2. Codes of Controller

public class AccountController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Login(userModel model)
    {    
        if (string.IsNullOrEmpty(model.username
            ) || string.IsNullOrEmpty(model.password))
        {
            return NotFound();
        }

       //var user = await _context.users.FirstOrDefaultAsync(x => x.username == model.username && x.password == model.password);

        //if (user != null)
        if (model.username.Equals("test") && model.password.Equals("123"))
        {
            HttpContext.Session.SetString("username", model.username);
        }
        else
            ViewBag.error = "Invalid Account";
         
        return View("Index");
    }

    [HttpGet]
    public IActionResult Logout()
    {
        HttpContext.Session.Remove("username");
        return RedirectToAction("Index");
    }
}

3. Codes of View

   <h3>Login Page</h3>
    @ViewBag.error
    <form method="post" asp-controller="account" asp-action="login">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>Username</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" value="Login"></td>
            </tr>
        </table>
    </form>

4. Codes of returning View when success

@using Microsoft.AspNetCore.Http;

<h3>Success Page</h3>
Welcome @Context.Session.GetString("username")
<br>
<a asp-controller="account" asp-action="logout">Logout</a>

Test result

enter image description here

Upvotes: 2

Related Questions