c# - ViewBag 没有向 View 发送任何值

标签 c# asp.net-core model-view-controller

在 ASP.NET Core MVC 中,我在创建登录面板时遇到问题,我在用户登录帐户后使用 session ,并将 session 值存储在 ViewBag 中。但是 ViewBag 内部没有获取任何值,而是获取了 null 值。

这是 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();
        }

这是 View 索引.cshtml

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

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

登录.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>

最佳答案

ASP.NET Core 中的 session 和状态管理

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


这里是如何在 ASP.NET Core 中使用 Session 的演示。

<强>1。启动配置代码

ConfigureServices 中的AddSession,Configure 中的UseSession

 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。 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。 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。成功返回View的代码

@using Microsoft.AspNetCore.Http;

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

测试结果

enter image description here

关于c# - ViewBag 没有向 View 发送任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63880461/

相关文章:

c# - 是否有任何 SQL Server Serilog 接收器支持 .Net Core

asp.net-core - Blazor 服务器页面单元测试 - 如何模拟 Blazor 服务器页面中使用的辅助 signalR 客户端连接

php - 无法在 codeigniter 中显示我的数据库

ruby-on-rails - Railscast 中的建筑测量 Rails 5

java - 查看 Web 应用程序的一部分 - 什么技术可以实现相当密集的 GridView ?

c# - DateTimeKind.Utc 与 DateTimeKind.Local

c# - 如何在异步函数中发送参数值

c# - 如何整齐查询对应的对象数组项?

asp.net-core - RedirectToAction 被忽略

ssl - 在 AWS 中调用 IdentityServer4 时获取 "IDX10108: The address specified is not valid as per HTTPS scheme"