NullReferenceException on DropDownListFor after [HttpPost]
In my application I'am populating a dropdownlist from database using ADO Entity Framework, after this when i try to submit the form the value of the dropdown list it is giving Null reference exception.
Error Code (in INDEX.ASPX)
<%: Html.DropDownListFor(model => model.race, Model.Races, "--Select--")%> <--error
<%: Html.ValidationMessageFor(model => model.race)%>
CONTROLLER (in NewPersonController)
public ActionResult Index()
{
Person person= new Perso开发者_如何学Cn();
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 (in 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");
}
}
IN VALIDATION MODEL
[MetadataType(typeof(Person_Validation))]
public partial class Person {
}
public class Person_Validation
{
[Required(ErrorMessage = "Required race")]
public string race
{
get;
set;
}
}
Can you help me please? Thank you.
In the POST method you have to give the same type of model to the view.
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid)
{
personRepo.Add(person);
personRepo.Save();
}
return View(new PersonFormViewModel(person));
}
You're not passing the ViewModel in the post action.
[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));
}
Or maybe
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) //Also not enter the race parameter
{
personRepo.Add(person);
personRepo.Save();
}
return RedirectToAction("Index");
}
精彩评论