如何在SQL Server中保存更改?

问题描述 投票:1回答:4

我试图为ApplicationUser.cs添加一个控制器,这样当管理员登录时,他们可以查看、编辑、删除dbo.AspNetUsers表中的任何记录,但是我认为我做错了。这个运行错误 "NullReferenceException.Object reference not set to an instance of the dbo.AspNetUsers"。NullReferenceException: Object reference not set to an instance of an object. "Any idea?

AdminController.View : ` @model Application:

public AdminController (ApplicationDbContext application)
{
    _application = application;

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


        [HttpPost]
        public async Task<ActionResult> ActiveUser(ApplicationUser Model)
        {
            var active = await _application.Users.FindAsync(Model.Email);

            Model.IsActive = true;
            active.IsActive = (Model.IsActive==true);

         await _application.SaveChangesAsync(); 

            return View();
        }

View : ` @model ApplicationUser.

            <input asp-for="IsActive" class="form-control" />
            <span asp-validation-for="IsActive" class="text-danger"></span>
        </div>
        <button type="submit" class="btn btn-success">ok</button>`
sql-server asp.net-core entity-framework-core asp.net-core-mvc asp.net-core-identity
4个回答
2
投票

你实际上从未在用户对象上设置IsActive。注意'='和'=='之间是有区别的。

试试这个代码。

 ApplicationUser active = await _application.Users.FindAsync(Model.Email);
 active.IsActive = true;
 _application.Update(active);
 await _application.SaveChangesAsync();

2
投票

错误信息表明你正试图从一个空引用访问属性。根据提供的代码,有两个可能的原因。

  1. await _application.Users.FindAsync(Model.Email); "没有找到用户并返回null,因此,当你尝试执行 "active.IsActive = (Model.IsActive==true); "时,你得到了异常。

  2. "Model "变量没有得到一个实例,你得到的是一个空引用异常。你需要验证你是在 "POST "中发送有效载荷,并且,用"[FromBody]"属性来装饰 "Model "参数。请看下面的内容。

[HttpPost]
public async Task<ActionResult> ActiveUser([FromBody]ApplicationUser Model)
{
  // Always check the parameters....
  if (Model == null)
  {
     return View();
  }

  var active = await _application.Users.FindAsync(Model.Email);

  // Always verify if found...
  if (active == null)
  {
    Response.StatusCode=404;
    return View(); 
  }

  active.IsActive = (Model.IsActive==true);

  await _application.SaveChangesAsync(); 

  return View();
}

1
投票

你需要为"[FromBody]"属性赋值 Model.IsActive:

if (active.IsActive == false) 
{ 
    Model.IsActive = (active.IsActive == true); 
}
_application.Update(active);
await _application.SaveChangesAsync(); 
return View();

1
投票

你的代码似乎是正确的。但似乎你需要通过 model 反对 View. 在你的情况下,似乎你的 View 需要对象 active 要通过。

试试 return View(active); 而不是 return View().

© www.soinside.com 2019 - 2024. All rights reserved.