2008-11-20 72 views
8

我試圖在ASP.NET MVC中重複使用相同的ViewUserControl時避免這樣的代碼。有什麼建議麼?如何在ASP.NET.NET MVC中乾淨地重用編輯/新視圖

<% 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> 
<%} %> 

回答

12

我一直在創造新的和編輯不同的意見,否則感覺就像我的應用程序邏輯開始蔓延到我的看法。同樣,我對「創建和更新」有不同的控制器操作。也許更好的方法是將兩個視圖共享的位移到用戶控件並執行RenderPartial。這樣,您可以使用單一模式獲得乾淨的視圖,但只能編寫一次通用部件。

+0

這是我在做什麼,但我還是要設置提交按鈕的文字。 – 2008-11-20 15:46:59

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> 
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" />