在我的应用程序中,我使用ADO实体框架从数据库填充下拉列表,在此之后,当我尝试提交表单下拉列表的值时,它给出了空引用异常。
错误代码(在INDEX.ASPX中)
<%: Html.DropDownListFor(model => model.race, Model.Races, "--Select--")%> <--error
<%: Html.ValidationMessageFor(model => model.race)%>
CONTROLLER(在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
}
MODEL(在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;
}
}
你能帮帮我吗?谢谢。
答案 0 :(得分:1)
在POST方法中,您必须为视图提供相同类型的模型。
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid)
{
personRepo.Add(person);
personRepo.Save();
}
return View(new PersonFormViewModel(person));
}
答案 1 :(得分:0)
您没有在后期操作中传递ViewModel。
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) //Also not enter the race parameter
{
personRepo.Add(person);
personRepo.Save();
}
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 RedirectToAction("Index");
}