ASP.NET MVC - using the same form to both create and edit

前端 未结 10 811
温柔的废话
温柔的废话 2021-01-30 05:27

Whats the best practice approach to creating a form that is used to both create new models and edit existing models?

Are there any tutorials that people can point me in

10条回答
  •  再見小時候
    2021-01-30 05:57

    this is not always the best practice because it depends on the case, here's how i did it

    1/ i combined the controller actions for create and edit

    public PartialViewResult Creedit(string id = null)
    {
        if (id == null)
        {
            // Create new record (this is the view in Create mode)
            return PartialView();
        }
        else
        {
            // Edit record (view in Edit mode)
            Client x = db.ClientSet.Find(id);
            if (x == null) { return PartialView("_error"); }
            // ...
            return PartialView(x);
        }
    }
    
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Creedit(Client x)
    {
        if (x.id == null)
        {
            // insert new record
        }
        else
        {
            // update record
        }
    }
    

    2/ i combined the edit and create views into one view i call Creedit

    // if you need to display something unique to a create view
    // just check if the Model is null
    @if(Model==null){
    }
    

    so i have 1 view and 2 actions (1 post and 1 get) instead of 2 views and 4 action.

提交回复
热议问题