I Got an error While submit "Object reference not set to an instance of an object" mvc2
I Got an error While submit "Object reference not set to an instance of an object" mvc2
View page
<%@ 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") %>
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(EventInfo EventInfo)
{
try
{
if (ModelState.IsValid)
{
EventModel.Create(EventInfo);
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
Model
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.ExecuteRead开发者_开发知识库er(cmd);
while (Datareader.Read())
{
Timezone.Add(new KeyValuePair<String, String>(Datareader["ABBR"].ToString(), Datareader["NAME"].ToString()));
}
return Timezone;
}
}
Plz give me the solution.
You need to repopulate the data for the dropdown in the [HttpPost] parts of the Create
action just like I'm guessing you are doing in the GET version of your Create
action. When you do a return View(Model)
in the HttpPost action it literally returns that HTML view and it needs all the supporting data too just like in the 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);
}
}
So at least two errors:
- When save succeeds why are you returning same view as if save fails?
- When save fails, need to pass in the EventInfo to the view (and populate viewdata/viewbag if needed for DropDownList)
精彩评论