如何在Asp.NET MVC中干净地重用编辑/新视图

时间:2008-11-20 05:56:15

标签: .net asp.net-mvc

在ASP.NET MVC中重用相同的ViewUserControl时,我试图避免这样的代码。有什么建议吗?

<% if (ViewContext.ViewData["editMode"].ToString() == "edit"){ %>
    <%= Html.SubmitButton("submit", "Update Brand")%><span class="or">Or</span><a href="#" class="cancel">Cancel</a>
<% } else { %>
    <%= Html.SubmitButton("submit", "Create New Brand")%><span class="or">Or</span><a href="#" class="cancel">Cancel</a>
<%} %>

而且......

<% if (ViewContext.ViewData["editMode"].ToString() == "edit"){ %>
    <h1 class="edit">Edit Brand Details</h1>
<% } else { %>
    <h1 class="create">Create A New Brand</h1>
<%} %>

3 个答案:

答案 0 :(得分:12)

我总是为New和Edit创建单独的视图,否则感觉我的应用程序逻辑开始蔓延到我的视图中。同样,我对Create和Update有不同的控制器操作。或许更好的方法是获取两个视图共享的位并将它们移动到用户控件并执行RenderPartial。这样,您可以使用单一模式获得干净的视图,但只能编写一次公共部分。

答案 1 :(得分:9)

为您的实体创建一个(或多个)部分视图(使用联系人实体的示例) - IdChange.ascx(显示Id和更改信息) - PersonalInfo.ascx - Address.ascx

仅在编辑视图中需要IdChange.ascx

创建两个单独的视图以进行编辑和创建,然后使用RenderPartial将模型数据带到视图中。 Create.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm())
   { %>
<fieldset>
    <legend>Create a new contact</legend>
    <div id="pagecontent">
        <div id="left">
        </div>
        <div id="center">
            <% Html.RenderPartial("PersonalInfo", Model); %>
        </div>
    </div>

    <p>
        <input type="submit" value="Create" />

Edit.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm())
   { %>
<fieldset>
    <legend>Edit existing contact</legend>
    <div id="pagecontent">
        <div id="left">
            <% Html.RenderPartial("IdChange", Model); %>
        </div>
        <div id="center">
            <% Html.RenderPartial("PersonalInfo", Model); %>
        </div>
    </div>

    <p>
        <input type="submit" value="Edit" />

答案 2 :(得分:2)

<% string submitLabel = (ViewData["editMode"].ToString() == "edit") ? "Update Brand" : "Create New Brand" %>
<%= Html.SubmitButton("submit", submitLabel)%><span class="or">Or</span><a href="#" class="cancel">Cancel</a>

如果您有多个这样的标签,可以在页面顶部定义它们。

<% 
  string submitLabel = (ViewData["editMode"].ToString() == "edit") ? "Update Brand" : "Create New Brand";
  string h1Class = (ViewData["editMode"].ToString() == "edit") ? "edit" : "create";
  string h1Label = (ViewData["editMode"].ToString() == "edit") ? "Edit Brand Details" : "Create a New Brand";
%>


<h1 class="<%= h1Class %>"><%= h1Label %></h1>