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 the direction of?
Luckily, the answer is yes. Combining ASP.NET Webforms and ASP.NET MVC in one application is possible—in fact, it is quite easy. The reason for this is that the ASP.NET MVC framework has been built on top of ASP.NET.
Razor Page is similar to the HTML page but it loads data easily. A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself.
NerdDinner will really show the way.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>" MasterPageFile="~/Views/Shared/Site.Master" %> <asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server"> Host a Nerd Dinner </asp:Content> <asp:Content ID="Create" ContentPlaceHolderID="MainContent" runat="server"> <h2>Host a Dinner</h2> <% Html.RenderPartial("DinnerForm"); %> </asp:Content>
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>" MasterPageFile="~/Views/Shared/Site.Master" %> <asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server"> Edit: <%:Model.Title %> </asp:Content> <asp:Content ID="Edit" ContentPlaceHolderID="MainContent" runat="server"> <h2>Edit Dinner</h2> <% Html.RenderPartial("DinnerForm"); %> </asp:Content>
<%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NerdDinner.Models.Dinner>" %> <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script> <% Html.EnableClientValidation(); %> <%: Html.ValidationSummary("Please correct the errors and try again.") %> <% using (Html.BeginForm()) { %> <fieldset> <div id="dinnerDiv"> <%:Html.EditorForModel() %> <p> <input type="submit" value="Save" /> </p> </div> <div id="mapDiv"> <%: Html.EditorFor(m => m.Location) %> </div> </fieldset> <% } %>
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.
Scott Gu will show the way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With