在我的應用程序中,我使用ADO實體框架從數據庫填充下拉列表,在此之後,當我嘗試提交表單的下拉列表的值時,它將提供Null引用異常。DropDownListFor在[HttpPost]後的NullReferenceException
出錯代碼(在的Index.aspx)
<%: Html.DropDownListFor(model => model.race, Model.Races, "--Select--")%> <--error
<%: Html.ValidationMessageFor(model => model.race)%>
控制器(在NewPersonController)
public ActionResult Index()
{
Person person= new Person();
return View(new PersonFormViewModel(person));
}
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) //Also not enter the race parameter
{
personRepo.Add(person);
personRepo.Save();
}
return View(); // When return the view I get the error
}
模型(PersonFormViewModel)
public class PersonFormViewModel
{
public Person Person {
get;
private set;
}
public SelectList Races
{
get;
private set;
}
public string race
{
get { return Person.race; }
set { Person.race = value; }
}
public PersonFormViewModel(Person person)
{
Person = person;
RaceRepository repository = new RaceRepository();
IList<Race> racesList= repository.FindRaces().ToList();
IEnumerable<SelectListItem> selectList =
from c in racesList
select new SelectListItem
{
Text = c.race,
Value = c.id.ToString()
};
Races = new SelectList(selectList, "Value", "Text");
}
}
的驗證模型
[MetadataType(typeof(Person_Validation))]
public partial class Person {
}
public class Person_Validation
{
[Required(ErrorMessage = "Required race")]
public string race
{
get;
set;
}
}
你能幫助我嗎?謝謝。
的[什麼是.NET一個NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – 2011-06-01 14:37:57