MVC DropDownList用于空引用

时间:2019-02-04 07:30:41

标签: c# asp.net-mvc

此模型用于定义视图:

namespace OnlineStore.ViewModels
{
    public class SubCategoryVM
    {
        [Key]
        public int ID { get; set; }
        [Required]
        public virtual string Name { get; set; }
        [Required(ErrorMessage = "Parent Category Name is required")]
        public virtual string ParentName { get; set; }
        public IEnumerable<SelectListItem> categoryNames { get; set; }
    }
}

内部控制器:

public ActionResult createSubCategory()
{
    SubCategoryVM model = new SubCategoryVM();
    var cNames = db.Categories.ToList();
    model.categoryNames = cNames.Select(x
        => new SelectListItem
        {
            Value = x.Name,
            Text = x.Name
        });
    return View(model);
}
[HttpPost]
public ActionResult createSubCategory(int? id, SubCategoryVM model)
{
    SubCategory sc = new SubCategory();
    if (ModelState.IsValid)
    {
        sc.ParentName = model.ParentName;
        sc.Name = model.Name;
    }
    return View();
}

并查看:

@model OnlineStore.ViewModels.SubCategoryVM        

<div class="form-group">
            @Html.LabelFor(model => model.ParentName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.ParentName, Model.categoryNames, "--Please select an option--", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ParentName, "", new { @class = "text-danger" })
        </div>

这段代码在行@Html.DropDownListFor(model => model.ParentName, Model.categoryNames, "--Please select an option--", new { @class = "form-control" })上引发了空引用异常:

Model.categoryName(对象引用未设置为对象的实例)。

请帮助我调试它。

先谢谢了。

1 个答案:

答案 0 :(得分:0)

问题是当您发布表单并在表单无效的情况下返回带有表单数据的View时,模型中的categoryNames变为空,您必须在返回{再次查看模型。

因此,如下更新您的categoryNames发布方法:

createSubCategory