我是ASP.NET MVC的新手,我試圖創建一個非常簡單的博客類型網站,作爲學習如何工作的一種手段。但是,從註釋表單發佈到模型爲null並且我無法說明原因時,我遇到了問題。無法找出爲什麼模型在回發中爲null?
在博客文章頁面上,我有一個「添加註釋」鏈接,它調用某個JQuery來呈現強類型化爲CommentModel的局部視圖。鏈接通過在博客帖子的ID以及和部分的編碼方式類似於:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Blog.Models.CommentModel>" %>
<% using (Html.BeginForm())
{ %>
<%: Html.HiddenFor(x => x.Post.ID) %>
<%: Html.HiddenFor(x => x.CommentID) %>
<%: Html.TextBoxFor(x => x.Name) %><br />
<%: Html.TextBoxFor(x => x.Email) %><br />
<%: Html.TextBoxFor(x => x.Website) %><br />
<%: Html.TextAreaFor(x => x.Comment) %><br />
<input type="submit" value="submit" />
<% } %>
的CommentsModel簡單,看起來像這樣(我沒有應用任何驗證或任何東西):
public class CommentModel
{
public BlogPost Post { get; set; }
public int CommentID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Website { get; set; }
public string Comment { get; set; }
}
然後這應該發佈到一個簡單的控制器操作,該操作會將註釋添加到數據庫並將用戶返回到頁面。爲了簡便起見,我已經去掉了大部分的代碼,但它看起來類似於:張貼評論表單時
[HttpPost]
public ActionResult CommentForm(CommentModel model)
{
if (ModelState.IsValid)
{
}
else
{
}
}
一切正常,只是,註釋型號爲NULL。我無法弄清楚爲什麼這是空的。當我查看呈現的部分視圖的來源時,我可以看到「Post.ID」填充了正確的ID,但是在提交表單時會丟失。
我在這裏錯過了一些明顯的東西嗎?我在過去設置了類似於此的表單,並且工作正常,我不明白爲什麼它不是現在。提前致謝。
後來編輯:
我已經輸入了錯誤的代碼,並改變從public ActionResult CommentForm(CommentModel comment)
這是導致問題的public ActionResult CommentForm(CommentModel model)
。
感謝您的幫助。
感謝您發佈此信息,我能夠從該答案中解決問題。我仔細檢查了我的代碼,問題是我把控制器的帖子設置爲(CommentsModel評論) - 這是不工作...愚蠢的錯誤!謝謝您的幫助。 – NickK