我收到错误提交“对象引用未设置为对象的实例”mvc2
查看页面
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<EventListing.Models.EventInfo>" %>
<%= Html.DropDownListFor(model => model.SelectedTimeZone, Model.TimeZones, "Select Timezone") %>
控制器
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(EventInfo EventInfo)
{
try
{
if (ModelState.IsValid)
{
EventModel.Create(EventInfo);
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
模型
public SelectList TimeZones { get; set; }
private string selectedTimeZone = "";
public string SelectedTimeZone
{
get { return selectedTimeZone; }
set { selectedTimeZone = value; }
}
public static IList<KeyValuePair<string, string>> getTIMEZOMES
{
get
{
Dbhelper DbHelper = new Dbhelper();
IList<KeyValuePair<String, String>> Timezone = new List<KeyValuePair<String, String>>();
DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM TMP_TIMEZONES");
DbDataReader Datareader = DbHelper.ExecuteReader(cmd);
while (Datareader.Read())
{
Timezone.Add(new KeyValuePair<String, String>(Datareader["ABBR"].ToString(), Datareader["NAME"].ToString()));
}
return Timezone;
}
}
Plz给我解决方案。
答案 0 :(得分:1)
您需要重新填充Create
操作的[HttpPost]部分中的下拉列表数据,就像我猜测您正在执行Create
操作的GET版本一样。当您在HttpPost操作中执行return View(Model)
时,它会直接返回该HTML视图,并且它也需要所有支持数据,就像在GET中一样!
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(EventInfo EventInfo)
{
try
{
if (ModelState.IsValid)
{
EventModel.Create(EventInfo);
return RedirectToAction("Index");
}
// MISSING model in below call plus likely viewdata/viewbag for dropdownlist
// why are you returning same view as returned when error? normally this is a RedirectToAction("DisplayEvent") or similar!
return View(EventInfo);
}
catch
{
// MISSING model in below call plus likely viewdata/viewbag for dropdownlist
return View(EventInfo);
}
}
所以至少有两个错误: