我有以下内容ViewModel
:
public class CategoryViewModel
{
public Category Category { get; set; }
public IList<Category> Categories { get; set; }
public IList<Product> Products { get; set; }
public IEnumerable<SelectListItem> CategorySelectItems
{
get { var ret = new List<SelectListItem>();
if(Categories==null)
return ret;
ret.AddRange(Categories.Where(x => (Category == null || x.Id !=
Category.Id)).Select(category => new SelectListItem
{ Text = category.Name, Value =
category.Id.ToString()}));
return ret;
}
}
public CategoryViewModel(){}
}
以下是控制器:
namespace mysite.com.Controllers{
public class CategoryController : Controller{
private IRepository<Category> _repository;
private IRepository<Product> _productRepo;
private CategoryViewModel _categoryViewModel;
public CategoryController(){
_repository = new CategoryRepository();
_productRepo = new ProductRepository();
}
[HttpGet]
public ActionResult Index(){
return View(new CategoryViewModel{Categories=_repository.GetAll()});
}
[HttpGet]
public ActionResult Add(){
return View(new CategoryViewModel{
Category = new Category(), Categories= _repository.GetAll()});
}
[HttpPost]
public ActionResult Add(CategoryViewModel category){
if (ModelState.IsValid){
_repository.Save(category.Category);
return RedirectToAction("Index");
}
return View(category);
}
}
}
这是我认为的代码:
@model mysite.com.ViewModels.CategoryViewModel
@using (Html.BeginForm("Add", "Category", FormMethod.Post))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Add Category</legend>
@Html.HiddenFor(x => x.Category.Id)
<div class="editor-label">
@Html.LabelFor(x => x.Category.Name)
</div>
<div class="editor-field">
@Html.EditorFor(x => x.Category.Name)
@Html.ValidationMessageFor(x => x.Category.Name)
</div>
<div class="editor-label">
@Html.LabelFor(x => x.Category.ParentCategory)
</div>
<div class="editor-field">
@Html.DropDownList("ParentCategory",
Model.CategorySelectItems,"--select parent category--")
@Html.ValidationMessageFor(x => x.Category.Name)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
但是在我的控制器的[HttpPost] Add
方法中,category
对象(类型CategoryViewModel
)是空的:(
我做错了什么?