有人可以解釋爲什麼模型對象爲null。我檢查了通過網絡發佈的帖子值,並且它們都被填充。錯誤發佈ASP.NET MVC中的編輯數據
使用VS2010 Beta 2,WinXp SP2,但是這在VS2008中工作??!
死亡消息的黃屏
Server Error in '/' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 17: <p> Line 18: <label for="id">id:</label> Line 19: <%= Html.TextBox("id", Model.id) %> <--Error Line 20: <%= Html.ValidationMessage("id", "*") %> Line 21: </p>
控制器代碼
的[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Contact contactToEdit)
{
if (contactToEdit.FirstName.Trim().Length == 0)
ModelState.AddModelError("FirstName", "First name is required.");
if (contactToEdit.Lastname.Trim().Length == 0)
ModelState.AddModelError("LastName", "Last name is required.");
if (contactToEdit.Phone.Length > 0 && !Regex.IsMatch(contactToEdit.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
ModelState.AddModelError("Phone", "Invalid phone number.");
if (contactToEdit.Email.Length > 0 && !Regex.IsMatch(contactToEdit.Email, @"^[\w-\.][email protected]([\w-]+\.)+[\w-]{2,4}$"))
ModelState.AddModelError("Email", "Invalid email address.");
if (!ModelState.IsValid)
return View();
try
{
// TODO: Add update logic here
var con = (from c in _entities.Contacts
where c.id == contactToEdit.id
select c).FirstOrDefault();
_entities.ApplyCurrentValues(con.EntityKey.EntitySetName, contactToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
摘錄視圖代碼
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<JQGallery.Models.Contact>" %>
...
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="id">id:</label>
<%= Html.TextBox("id", Model.id) %>
<%= Html.ValidationMessage("id", "*") %>
</p>
<p>
<label for="FirstName">FirstName:</label>
<%= Html.TextBox("FirstName", Model.FirstName) %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
...
實際上,這不是真的,因爲模型綁定。點擊此處查看更多信息:http://www.asp.net/learn/mvc/tutorial-36-cs.aspx –
模型綁定使用提交的表單值在OP的Edit方法中實例化和設置contactToEdit參數的屬性。它沒有實例化和填充可用於其View的Model對象。 (您教程中的示例鏈接僅使用View()方法工作,因爲該特定示例視圖不會嘗試訪問Model對象。) –
實際上,我向您發送了一個鏈接,僅指向「創建」操作,但編輯將工作於同樣的方式:http://www.asp.net/%28S%28pdfrohu0ajmwt445fanvj2r3%29%29/learn/mvc/tutorial-28-cs.aspx - 這個想法是因爲模型POST'ed到行動,當動作簡單地返回到視圖時,模型綁定會將其推回到瀏覽器。 –