我只是有一个关于 MVVM 设计模式的快速问题...我只是想知道我做事的方式是否“正确”?
我有一个这样的分类模式:
[Table("Category")]
public class CategoryModel
{
[Key]
public Int32 CategoryId { get; set; }
public string CategoryName { get; set; }
public Int32? Category_ParentID { get; set; }
public virtual CategoryModel Parent_Category { get; set; }
public virtual ICollection<CategoryModel> SubCategories { get; set; }
public Int16 CategoryOrder { get; set; }
public bool Deleted { get; set; }
}
“创建新类别”表单不需要所有这些,因此我创建了一个仅包含必填字段的 ViewModel:
public class CategoryViewModel
{
public string CategoryName { get; set; }
public Int32? Category_ParentID { get; set; }
}
创建新类别时,我将 ViewModel 作为参数发送,并使用 ViewModel 中的值创建新的 CategoryModel,如下所示:
if (ModelState.IsValid)
{
CategoryModel newCategory = new CategoryModel()
{
CategoryName = model.CategoryName,
Category_ParentID = model.Category_ParentID
};
//get the root node, and include it's subcategories
var categoryList = DatabaseContext.Categories.Include("SubCategories").Single(c => c.CategoryId == model.Category_ParentID);
//set the order of the category by getting the number of subcategories
if (categoryList.SubCategories.Count > 0)
newCategory.CategoryOrder = (Int16)(categoryList.SubCategories.Where(c => !c.Deleted).Max(c => c.CategoryOrder) + 1);
else
newCategory.CategoryOrder = 1;
//save the new category
DatabaseContext.Categories.Add(newCategory);
await DatabaseContext.SaveChangesAsync();
return PartialView("_CategoryModelItem", model);
} else {
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
这是执行 MVVM 设计模式的正确方法吗(即从 ViewModel 获取值,创建新模型 - 从 ViewModel 获取值 - 并写入数据库)?还是我误解了它是如何支持的?
还有
“查看”部分如何工作?我的意思是,如果我在 Controller 的 Index() 方法中列出一个类别及其所有子类别……我应该使用模型还是 View 模型来显示它们?因此,我需要添加将 ICollection 添加到 ViewModel 的需求,然后我是否应该使用 Entity Framework 和 Model 类获取数据,然后以某种方式将其提供给 ViewModel?
最佳答案
你是对的,但我有一些其他的提示给你:
- 不要使用 Model 后缀命名 Entity Framework 实体,使用 单数形式的数据库表名称
- 总是返回一个对象。如果你想返回一个对象列表,然后将这个列表包装到一个类中。它将帮助您使 ViewModel 更加灵活且易于扩展。使用包装类 如果你想返回一个单一的值(value)。我将这些对象称为 PageModels。
如果我想返回单个类别,那么我的编辑页面模型将如下所示:
public class CategoryEditPageModel
{
CategoryModel Category { get; set;}
//other data not directly related to category itself but needs to be visible on the page
User CategoryOwner { get; set; }
}
如果您想更新类别,则只发布 CategoryModel。
关于c# - ASP.Net MVC - 正确执行 MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25868820/