关于razor:ASP.NET MVC Single View用于CRUD操作

ASP.NET MVC Single View for CRUD operation

我正在研究ASP.NET MVC项目。我对CRUD操作中的视图有疑问。

在我看到的大多数示例中,每个CRUD操作(例如,Add,Edit,Delete)都使用单独的视图。现在,假设我的数据库中是否有100个表,并且每个表都需要通过View执行CRUD操作。最好为每个表创建这些单独的视图,还是创建一个可以为我创建这些视图的函数,例如下面?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public ActionResult CreateSubject()
{
    return View(Model.toList());
}

public ActionResult EditSubject()
{
    return View();
}

 public ActionResult DeleteSubject()
{
    return View();
}

我对控制器上的每个操作使用单独的操作,并创建一个处理所有字段的简单PartialView,然后使用"我的共享"文件夹中的共享视图加载我的部分视图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class CRUDController : Controller {
  public ActionResult Create() {
    return View(new CreateModel());
  }

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Create(CreateModel model) {
    if(ModelState.IsValid) {
      //save to db return view or redirect
    }

    return View(model);
  }

  public ActionResult Edit(it id) {
    var model = new EditModel();
    model = //load and map from db    
    return View(model);
  }

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Create(EditModel model) {
    if(ModelState.IsValid) {
      //save to db return view or redirect
    }

    return View(model);
  }
}

支持的接口:

1
2
3
4
5
6
7
public interface ICreateModel {
}


public interface IEditModel {
  int Id {get;set;}
}

CreateModel.cs:

1
2
3
public class CreateModel : ICreateModel {
  public string SomeProp {get;set;}
}

EditModel.cs:

1
2
3
public class EditModel : CreateModel, IEditModel {
  public int Id {get;set;}
}

_create.cshtml:

1
2
@model CreateModel
@Html.TextBoxFor(x=>x.SomeProp)

Create.cshtml:

1
2
3
4
5
@model ICreateModel    
@using(Html.BeginForm) {
  @Html.Partial("_create")
  <input type="submit" value="Submit"/>
}

Edit.cshtml

1
2
3
4
5
6
@model EditModel
@using(Html.BeginForm) {
  @Html.Partial("_create")
  @Html.HiddenFor(x=>x.Id)
  <input type="submit" value="Submit"/>
}

这是我如何处理多个CRUD操作的示例(至少在显示表单形式方面)。您的"创建/编辑"视图中显然会有更多内容

通过将Edit.cshtml和Create.cshtml放置在Shared文件夹中,当您从具有这些名称的操作中返回视图时,默认情况下将使用它。默认情况下,视图引擎检查控制器的相应视图文件夹中的文件,然后查找"共享"。每个_create.cshtml部分都应位于相应命名的View文件夹中,并且它们将正确传递。