我对 MVC 还是很陌生,但仍然对 2 个案例的最佳和正确方法感到困惑,结果相同。假设某个用户应该为特定的根类别添加新的子类别。
情况 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" />
两种方式都一样,但第一种方式看起来不太安全,因为可以在客户端更改隐藏。第二种方式要长得多,想象一下对于客户端或产品等丰富对象的相同方式......我应该选择什么?还是有其他方法?