為什么這會給我一個物件空參考錯誤:
[HttpPost]
public ActionResult WriteNote(NotesModel note) //notes == null
{
SendToDB(note.Author, note.Title, note.Note);
return View(); //BREAKPOINT
}
這不會:
[HttpPost]
public ActionResult WriteNote(NotesModel model) //model is not null
{
SendToDB(model.Author, model.Title, model.Note);
return View(); //BREAKPOINT
}
我花了大約 2 個小時試圖找出問題所在,我只是偶然發現了這一點,但不知道為什么會這樣。無論我為物件選擇什么名稱,任何事情都會做,但請注意......
誰能解釋一下?
- - -編輯:
要重新創建此問題,請執行以下操作
創建一個新的 ASP.NET (Framework 4.8.1) MVC 專案。創建一個名為“NotesModel.cs”的模型,其內容如下:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebsiteProject.Models
{
public class NotesModel
{
[Display(Name = "Author")]
public string Author { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Note")]
public string Note { get; set; }
}
}
接下來創建一個名為“NotesController.cs”的控制器,其內容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebsiteProject.Models;
using System.Windows;
namespace WebsiteProject.Controllers
{
public class NotesController : Controller
{
public ActionResult WriteNote()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult WriteNote(NotesModel note)
{
if (note == null) MessageBox.Show("IF YOU ARE SEEING THIS THEN note == NULL");
return View();
}
}
}
接下來轉到 NotesController.cs 檔案并右鍵單擊public ActionResult WriteNote()并選擇“添加視圖”,選擇 MVC 5 視圖。
對于模板選擇:創建
對于模型類,選擇 NotesModel
轉到新創建的視圖并啟動 webapp,填寫三個文本框并提交。
現在您應該看到一個文本框告訴您 note == NULL,這顯然是錯誤的,它應該從表單接收到資料。
現在,如果您轉到 NotesController.cs 檔案并替換
public ActionResult WriteNote(NotesModel note)
有了這個
public ActionResult WriteNote(NotesModel somethingelse)
(在宣告中也note改為)somethingelseif
它將不再為 null 并實際從表單接收資料。if您可以通過在陳述句中插入斷點來檢查這一點。此外,訊息框現在不應該彈出。
我希望這足夠詳細以重現問題。
uj5u.com熱心網友回復:
引數名稱與表單欄位名稱匹配,因此對于您想要袋子還是只想要欄位感到困惑。嘗試作者或標題以確認。
uj5u.com熱心網友回復:
這是預期的行為。ASP.NET 使用引數的名稱來確定哪些表單元素映射到該引數。盡管您沒有顯示您的標記,但您似乎有一個(或多個元素)使用名稱model但不是note.
重命名引數或重命名 HTML 元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/531585.html
上一篇:C#控制器行為根據變數名改變
下一篇:MVC表單資料無法系結到模型
