[HttpPost]之后DropDownListFor上的NullReferenceException

时间:2011-06-01 14:34:10

标签: c# asp.net-mvc ado.net nullreferenceexception

在我的应用程序中,我使用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;
        }
    }
你能帮帮我吗?谢谢。

2 个答案:

答案 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");
}