最近学习asp.net core,遇到个问题_cshtml需要显示登录的用户名,不知道怎么调用,
研究了一下发现MVC 不同的view 和controller 的引用是可以通过model,下面看下怎么用。
1. model 中插入静态类用作中转
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AoT_test.Models { public class Users { public Int64 ID { get; set; } public int sn { get; set; } public string username { get; set; } public string password { get; set; } public string name { get; set; } public string phone { get; set; } } public static class UserDisplay { public static string userdisplay { get; set; } } }
2登录的controller 里面给model 赋值
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using AoT_test.Data; using AoT_test.Models; using Microsoft.Extensions.Logging; namespace AoT_test.Controllers { public class LoginController : Controller { private readonly ILogger<LoginController> _logger; private readonly AoT_testContext _context; public LoginController(ILogger<LoginController> logger, AoT_testContext context) { _logger = logger; _context = context; } public IActionResult Login(Users users) { var item = _context.Users.FirstOrDefault(m => m.username == users.username && m.password==users.password); if(item!=null) { UserDisplay.userdisplay = users.username; return Redirect("../Home/Index"); } else { return View(); } } } }
3._layout 中使用viewbag 绑定显示
<span class="user-info"> <small>管理员,</small> @{ string user = "未登录"; user = UserDisplay.userdisplay; ViewBag.temp= user; } @ViewBag.temp </span>
4.最终的显示