DropDownListFor对象引用未设置为对象的实例

时间:2012-02-09 19:21:41

标签: asp.net-mvc-3 drop-down-menu

我使用ModelView来创建DropDownList:

模型视图

public class CreateSubjectModel
{
    public Subject Subject { get; set; }
    public IEnumerable<SelectListItem> Careers { get; set; }
}

行动[HttpGet]

 public ActionResult Create()
    {
        CreateSubjectModel model = new CreateSubjectModel();

        List<SelectListItem> careerList = new List<SelectListItem>();
        foreach (var career in _careerManager.GetCareers())
            careerList.Add(new SelectListItem() { Text = career.Institution + " - " +     career.Name, Value = career.id.ToString() });    

        model.Careers = careerList;

        return View(model);
    } 

行动[HttpPost]

public ActionResult Create(CreateSubjectModel createSubjectModel)
        {
            try
            {
                _subjectManager.SaveSubject(createSubjectModel.Subject);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

观点:

  <div class="editor-field">
        @Html.DropDownListFor(model => model.Careers, Model.Careers)
        @Html.ValidationMessageFor(model => model.Careers)
    </div>

问题是,当我点击提交时,我遇到了这个问题:

**Object reference not set to an instance of an object.**
Description: An unhandled exception occurred during the execution of the current web   request. Please review the stack trace for more information about the error and where it  originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 47:         </div>
Line 48:         <div class="editor-field">
Line 49:             @Html.DropDownListFor(model => model.Careers, Model.Careers)
Line 50:             @Html.ValidationMessageFor(model => model.Careers)
Line 51:         </div>

我到处寻找,我找不到一个可以帮助我的工作示例或一些教程。 希望你能做到......

2 个答案:

答案 0 :(得分:3)

您可能在catch块中的代码中有一个例外情况。在这种情况下,在视图中你有异常,因为模型是null。

try
{
    _subjectManager.SaveSubject(createSubjectModel.Subject);
    return RedirectToAction("Index");
}
catch
{
    return View(); // problem here.. return View with model too.
}

答案 1 :(得分:0)

两件事:

首先,您没有创建将填充Subject模型的控件,因此Create操作中的控件为空。你没有发布那个模型,所以我不能告诉你razor语法应该是什么。

第二: 您正在绑定为列表本身创建下拉列表:

@Html.DropDownListFor(model => model.Careers, Model.Careers)

将您的模型更改为:

public class CreateSubjectModel
{
    public Subject Subject { get; set; }
    public IEnumerable<SelectListItem> Careers { get; set; }
    public int SelectedCareerId { get; set; }
}

和您的观点:

@Html.DropDownListFor(model => model.SelectedCareerId, Model.Careers)

此新属性将在Create操作中选择值。