这个问题已经在这里有一个答案:
该模型用于定义视图:
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(对象引用不设置为一个对象的一个实例)。
请帮我调试。
提前致谢。
问题是,当您发布形式和形式无效的情况下,返回与表单数据的视图,categoryNames
模型变得无效,你必须再次返回与模型视图之前重新填充categoryNames
。
因此,如下更新createSubCategory
POST方法:
[HttpPost]
public ActionResult createSubCategory(int? id, SubCategoryVM model)
{
SubCategory sc = new SubCategory();
if (ModelState.IsValid)
{
sc.ParentName = model.ParentName;
sc.Name = model.Name;
}
var cNames = db.Categories.ToList();
model.categoryNames = cNames.Select(x
=> new SelectListItem
{
Value = x.Name,
Text = x.Name
});
return View(model);
}