有人可以解释为什么模型对象为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到行动,当动作简单地返回到视图时,模型绑定会将其推回到浏览器。 –