我很新于MVC,仍然不清楚在两种情况下获得相同结果的最佳和适当方式。假设某些用户应该为特定根类别添加新的子类别。
情况1: SubCategory是由EF映射的类,其中所有属性都不可为空。
控制器:
[Authorize]
public ActionResult Create()
{
SubCategory subCategory = new SubCategory();
subCategory.RootCategoryID = 1;
return View(subCategory);
}
[Authorize]
[HttpPost]
public ActionResult Create(SubCategory thisSubCategory)
{
if (ModelState.IsValid)
{
//And some BL logic called here to handle new object...
}
}
视图:
@Html.HiddenFor(model => model.ID)
@Html.HiddenFor(model => model.RootCategoryID)
<h3>Sub Category Name: </h3>
@Html.EditorFor(model => model.CategoryName)
@Html.ValidationMessageFor(model => model.CtaegoryName)
<input id="btnAdd" type="submit" value="Add" />
案例 2: 将辅助类作为控制器的模型,并在提交后填充 EF 对象
控制器:
class SubCategoryHelper
{
public string Name { get; set; }
}
[Authorize]
public ActionResult Create()
{
SubCategoryHelper subCategory = new SubCategoryHelper();
return View(subCategory);
}
[Authorize]
[HttpPost]
public ActionResult Create(SubCategoryHelper thisSubCategory)
{
if (ModelState.IsValid)
{
SubCategory newSubCategory = new SubCategory();
newSubCategory.RootCategoryID = 1;
newSubCategory.CtaegoryName = thisSubCategory.Name;
//And some BL logic called here to handle new object...
}
}
查看:
子类别名称:
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
<input id="btnAdd" type="submit" value="Add" />
两种方法都可以达到相同的效果,但第一种方法看起来不太安全,因为客户端可能会更改隐藏字段。第二种方法要长得多,想象一下对于像客户或产品这样的复杂对象的相同方式......我应该选择哪种?还是有其他方法吗?