Combining Create and Index Views in one View in Asp.Net MVC



我的仪表板区域中有一个控制器,一个操作将类别作为要查看的列表返回,另一个操作创建新类别

我的行动:

public ActionResult Categories() {
return View(db.Categories.OrderBy(Categories => Categories.Name).ToList());
}

[HttpPost]
public RedirectToRouteResult NewCategory(string name, string address, string parentId) {
if (ModelState.IsValid) {
int? ParentID = null;
if (parentId != "null") {
ParentID = parentId.AsInt();
}
Category oCategory = new Category();
oCategory.Name = name;
oCategory.Address = address;
oCategory.ParentID = ParentID;
db.Categories.Add(oCategory);
db.SaveChanges();
db.Dispose();
db = null;
}
return RedirectToAction("Categories");
}

我在类别视图中有一个纯HTML表单,用于获取用户输入以创建一个新类别和一个表示我已经拥有的类别的块。

我有一个Select和几个Foreach循环,在我的表单中从父循环到子循环遍历类别

这是代码:

<select name="parentID" id="parentCategoryId">
<option value="null" selected>nothing</option>
@foreach (var Category in Model) {
if (Category.ParentID == null) {
<option value="@Category.ID">@Category.Name</option>
foreach (var SubCategory1 in Model) {
if (SubCategory1.ParentID == Category.ID) {
<option value="@SubCategory1.ID">
&nbsp;&nbsp;&nbsp;
»
&nbsp;
@SubCategory1.Name
</option>
foreach (var SubCategory2 in Model) {
if (SubCategory2.ParentID == SubCategory1.ID) {
<option value="@SubCategory2.ID">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
»
&nbsp;
@SubCategory2.Name
</option>
foreach (var SubCategory3 in Model) {
if (SubCategory3.ParentID == SubCategory2.ID) {
<option value="@SubCategory3.ID">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
»
&nbsp;
@SubCategory3.Name
</option>
}
}
}
}
}
}
}
}
</select>

在视图中,我使用从模型中获取数据

@model IEnumerable<project.Models.Category>

但我需要在这里使用另一个Model对象:

@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })

和验证操作!

问题是我该如何将这两种观点结合起来?

现在我陷入了这个错误:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

您需要创建模型:

public class CategoryModel {
public string Name {get;set;}
public string Address {get;set;}
pubic string ParentId {get;set;}
public IEnumerable<Category> Categories {get;set;}
}

在您的控制器中:

public ActionResult Categories() {
var model = new CategoryModel();
model.Categories = db.Categories.OrderBy(Categories => Categories.Name).ToList();
return View(model);
}
[HttpPost]
public RedirectToRouteResult NewCategory(CategoryModel model) {
if (ModelState.IsValid) {
int? ParentID = null;
if (model.ParentId != "null") {
ParentID = model.ParentId.AsInt();
}
Category oCategory = new Category();
oCategory.Name = Model.Name;
oCategory.Address = Model.Address;
oCategory.ParentID = ParentID;
db.Categories.Add(oCategory);
db.SaveChanges();
db.Dispose();
db = null;
}
return RedirectToAction("Categories");
}

并且在视图中:

@model project.Models.CategoryModel

现在您可以在同一视图中创建类似的字段:

@Html.EditorFor(Model=>model.Title)
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })

最新更新