我遇到了一个奇怪的问题....当我使用UpdateModel()
或TryUpdateModel()
时,一切正常。当我尝试自己绑定时(例如MyObject.FirstName = collection["FirstName"]
),我收到"Object reference not set to an instance of an object"
错误。
这有点难以解释,所以我将提供代码:
[HandleError]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
Model.Event evnt = new Redline.RedlineTimeAttack.Model.Event();
//When this is uncommented everything works fine.
//TryUpdateModel<Model.Event>(evnt);
//this will eventually lead to problems
evnt.Description = collection["Description"];
evnt.EndDate = enddate;
evnt.EventName = collection["EventName"];
evnt.IsActive = collection["IsActive"].Contains("true");
evnt.StartDate = startdate;
evnt.TrackId = trackId;
evnt.WebContent = collection["WebContent"];
if (!evnt.IsValid)
{
foreach (var error in evnt.GetRuleViolations())
{
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
}
//If there are no validation issues then no problem, redirecttoaction
//works properly
if (ModelState.IsValid)
{
model.Events.InsertOnSubmit(evnt);
model.SubmitChanges();
ViewData["ControlMode"] = "Edit";
return RedirectToAction("Edit");
}
else //returning to View so that user can correct issues causes a null reference error in the view (bombs at first Html.Textbox("ControlName"))
{
ViewData["Tracks"] = GetTracks();
return View("Create", evnt);
}
}
这是堆栈跟踪:
System.NullReferenceException was unhandled by user code
Message="Object reference not set to an instance of an object."
Source="System.Web.Mvc"
StackTrace:
at System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType)
at System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name)
at ASP.views_event_create_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer) in d:\TFSProjects\Redline Time Attack\Main\Source\Redline.RedlineTimeAttack.Web\Views\Event\Create.aspx:line 18
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Control.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in d:\TFSProjects\Redline Time Attack\Main\Source\Redline.RedlineTimeAttack.Web\Views\Shared\Site.Master:line 29
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Control.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
答案 0 :(得分:22)
我在这里找到了一些见解:http://forums.asp.net/p/1396019/3006051.aspx
如果您不想使用内置模型 绑定,然后使用Bultin验证 (SanjaySutar想要使用),适合每一个人 您需要添加ModelError 添加ModelValue: ModelState.AddModelError(“Name”,“Bad 名“);
ModelState.SetModelValue( “姓名”, ValueProvider [ “名称”]);
所以我更新了我的代码:
ModelState.SetModelValue("Description", new ValueProviderResult(ValueProvider["Description"].AttemptedValue, collection["Description"], System.Globalization.CultureInfo.CurrentCulture));
ModelState.SetModelValue("EventName", new ValueProviderResult(ValueProvider["EventName"].AttemptedValue, collection["EventName"], System.Globalization.CultureInfo.CurrentCulture));
ModelState.SetModelValue("EndDate", new ValueProviderResult(ValueProvider["EndDate"].AttemptedValue, collection["EndDate"], System.Globalization.CultureInfo.CurrentCulture));
ModelState.SetModelValue("StartDate", new ValueProviderResult(ValueProvider["StartDate"].AttemptedValue, collection["StartDate"], System.Globalization.CultureInfo.CurrentCulture));
ModelState.SetModelValue("TrackId", new ValueProviderResult(ValueProvider["TrackId"].AttemptedValue, collection["TrackId"], System.Globalization.CultureInfo.CurrentCulture));
ModelState.SetModelValue("WebContent", new ValueProviderResult(ValueProvider["WebContent"].AttemptedValue, collection["WebContent"], System.Globalization.CultureInfo.CurrentCulture));
我这样做的原因是因为我想要一个。在我的业务对象中完成所有(或尽可能多)验证,包括必填字段和b。我想在验证摘要中使用我自己的消息(例如“FieldX是必填字段。”而不是“需要值。”)。如果有更好的方法,请参阅我的另一个问题:ASP.NET MVC - Custom validation message for value types
答案 1 :(得分:0)
enddate,startdate和trackId来自哪里?这甚至不应该编译,但也许我只是愚蠢而没有看到他们的声明。我确定它只是看不到的地方,对吧?
确保所有这些表单值实际上也包含其中的内容。