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

前端 未结 10 981
温柔的废话
温柔的废话 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 06:05

    NerdDinner will really show the way.

    Create.aspx

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" MasterPageFile="~/Views/Shared/Site.Master"  %>
    
        Host a Nerd Dinner
    
    
        

    Host a Dinner

    <% Html.RenderPartial("DinnerForm"); %>

    Edit.aspx

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage"
        MasterPageFile="~/Views/Shared/Site.Master" %>
    
        Edit: <%:Model.Title %>
    
    
        

    Edit Dinner

    <% Html.RenderPartial("DinnerForm"); %>

    DinnerForm.ascx

    <%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    
    
    
    <% Html.EnableClientValidation(); %>
    <%: Html.ValidationSummary("Please correct the errors and try again.") %>
       <% using (Html.BeginForm())
          { %>
       
    <%:Html.EditorForModel() %>

    <%: Html.EditorFor(m => m.Location) %>
    <% } %>

    Take into account that this form is using Html.EditorForModel(), which is an innovative method for generating all the fields at once, and you have to study its disadvantages before using it. But you can easily take the rest of the example to separate your common form from the create and edit views.

    Finally you can view the controller code here if you are interested.

提交回复
热议问题