ASP.NET MVC Single View for CRUD operation

2019-09-04 14:58发布

问题:

I am working on a ASP.NET MVC project. I have a question about the View in a CRUD operation.

In most of the examples I have seen, separate views for each CRUD operation (e.g. Add, Edit, Delete) are used. Now imagine if I have 100 tables in my database, and each of them requires CRUD operations via a View. Is it best to create these separate Views for each table or create a function that would create these Views for me, such as below?

public ActionResult CreateSubject()
{
    return View(Model.toList());
}

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

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

回答1:

I use separate actions for each operation on my controller and create a simple PartialView that handles all the fields and then I use a shared View from my Shared folder that loads my partial view.

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);
  }
}

Supporting interfaces:

public interface ICreateModel {
}


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

CreateModel.cs:

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

EditModel.cs:

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

_create.cshtml:

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

Create.cshtml:

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

Edit.cshtml

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

This is an example of how I handle my multiple CRUD operations (at least in terms of showing forms for them). There would obviously be more content in your Create/Edit views

By placing the Edit.cshtml and Create.cshtml in the Shared folder, it'll be used by default when you return a view from an action with those names. By default the view engine checks the appropriate view folder for the controller for the file and then looks to Shared. Each of your _create.cshtml partial should be in the appropriately named View folders and they will be delivered correctly.