【发布时间】:2021-08-25 08:10:25
【问题描述】:
我正在尝试将当前的 userId 添加到我的对象中,但我得到一个 nullreferenceexception。 我正在使用带有(身份验证)的 c# .net 核心 MVC 项目。
我认为当我想创建一个新的设备对象时,userId 尚未启动,但我该如何解决?
控制器:
// POST: Device/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Device device)
{
if (ModelState.IsValid)
{
//get current userId
string userId = _userManager.GetUserId(HttpContext.User);
//create a device
int id = _deviceService.Create(device);
//set userId to the device
Device deviceToLinkToUser = _deviceService.FindById(id);
deviceToLinkToUser.User.Id = userId;
return RedirectToAction(nameof(Details), new { id = id });
}
return View(device);
}
服务:
public int Create(Device device)
{
_context.Devices.Add(device);
_context.SaveChanges();
return device.Id;
}
数据类:
public class Device
{
public int Id { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public Damage Damage { get; set; }
[Display(Name = "Damage")]
public int DamageId { get; set; }
public CustomUser User { get; set; }
}
查看:
@model RepairAtDems.Data.Device
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Device</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Brand" class="control-label"></label>
<input asp-for="Brand" class="form-control" />
<span asp-validation-for="Brand" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Model" class="control-label"></label>
<input asp-for="Model" class="form-control" />
<span asp-validation-for="Model" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DamageId" class="control-label"></label>
<select asp-for="DamageId" class="form-control" asp-items="ViewBag.DamageId"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
我错过了什么吗?
【问题讨论】:
标签: entity-framework-core asp.net-core-mvc asp.net-identity