我在ASP.NET Core項目中創建了模型。該模型具有「Id」屬性。當我想在數據庫中保存一個模型時,它說模型的ID爲空。下面是代碼:ASP.NET Core - 模型的ID /密鑰無法獲得值
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveMessage(MessageViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var message = new MessageModel
{
SenderName = await _userManager.GetUserNameAsync(await _userManager.GetUserAsync(User)),
Title = model.Title,
Email = model.Email,
Message = model.Message,
SavedDate = DateTime.Now,
Sent = false
};
var userMessage = new UserMessage
{
ApplicationUser = await _userManager.GetUserAsync(User),
MessageModel = message
};
_context.MessageModel.Add(message);
_context.UserMessage.Add(userMessage);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(HomeController.Home), "Home");
}
return RedirectToAction(nameof(MessageController.EditMessage), "Message", model);
}
這裏是模型:
public class MessageModel
{
public string Id { get; set; }
public string SenderName { get; set; }
public string Title { get; set; }
public string Email { get; set; }
public string Message { get; set; }
public DateTime SavedDate { get; set; }
public bool Sent { get; set; }
public List<UserMessage> UserMessages { get; set; }
}
我怎麼可以給一個值的id? 謝謝!
請發佈相關型號代碼,並告訴我們哪個型號有錯誤。 –
如果Id不在模型中。它意味着你需要在視圖中提供值,例如通過使用輸入隱藏的'@ Html.Hidden()' –