2011-04-17 60 views
1

我有一個包含我的表單輸入(文本框)的局部視圖。我有2個其他部分視圖使用這種相同的形式。一個用於添加產品,另一個用於編輯產品。我怎樣才能讓我的視圖模型

此表單使用視圖模型(讓我們稱之爲CoreViewModel)。現在編輯產品有幾個字段,然後添加一個產品。

我想知道如何添加這些額外的領域,而沒有他們出現在添加產品形式?

我不能將這些額外的字段添加到編輯產品視圖中,他們必須在CoreViewModel中,否則我認爲它的樣式將是一場噩夢。

我正想着可能有一個基類,然後進行編輯。我會給它發送一個繼承這個基類的視圖模型。

檢查視圖模型是否屬於此繼承類而不是基類,以及它是否不是基類呈現代碼。

這樣我就不會將編輯特定的代碼粘貼到添加視圖和編輯視圖都可以訪問的CoreViewModel中。

我希望這種說法有道理。

感謝

編輯

使用穆罕默德·阿迪爾·扎希德代碼,我基地,我想我得到它的工作

public class CreateViewModel 
    { 
    ...... 
    ...... 
    } 

    public class EditViewModel:CreateViewModel{ 
     public string AdditionalProperty1{get;set;} 
     public string AdditionalProperty2{get;set;} 
    } 

Controller 

    EditViewModel viewModel = new EditViewModel(); 
    // add all properties need 
    // cast it to base 
    return PartialView("MyEditView", (CreateViewModel)viewModel); 

View 1 

    @Model CreateViewModel 
    @using (Html.BeginForm()) 
    { 
     @Html.Partial("Form", Model) 
    } 

Form View 

@Model CreateViewModel 
// all properties from CreateView are in here 
// try and do a safe case back to an EditViewModel 
@{EditViewModel edit = Model as EditViewModel ;} 

// if edit is null then must be using this form to create. If it is not null then it is an edit 
@if (edit != null) 
{  // pass in the view model and in this view all specific controls for the edit view will be generated. You will also have intellisense. 
     @Html.Partial("EditView",edit) 
} 

當你郵寄回你的編輯操作的結果只取在EditViewModel中並將其轉換回您的底座。那麼你將擁有所有的財產,因爲它似乎工作

+0

您可以在每個視圖中顯示所需的字段。你如何在意見上建立表格? – tomasmcguinness 2011-04-17 17:35:47

+0

@tomasmcguinness - 我想避免重複的數據。我的意思是我不想複製10個字段,因爲我有2個字段需要添加。 – chobo2 2011-04-17 18:13:29

回答

0

我經常閱讀人們建議反對這樣的事情。他們經常敦促每個視圖都有視圖模型(即使是編輯併爲此創建相同實體的視圖)。再次,這一切都歸結於你在做什麼。編輯時可能有不同的數據註釋,併爲不同的驗證需求創建視圖,但如果它們相同,我們可能有一點要使用相同的視圖模型進行創建和編輯。爲了解決你的情況,我不能找出幾個選項。首先,在你的視圖模型的布爾屬性告訴你,如果它是和編輯或創建並有條件地呈現您的屬性上查看

public class MyViewModel 
{ 
    public string P1{get;set;} 
    .... 
    public boolean Editing{get;set;} 
} 

集編輯屬性設置爲false在創建的ActionResult,並真正在編輯ActionReult。這是最簡單的方法。第二個是髒兮兮的,但你會覺得使用這種技術。您可以使用C#4.0的動態行爲。讓你的頁面在頁面的iherits指令中動態地繼承(我使用aspx視圖引擎)。然後有一個創建視圖模型:

public class CreateViewModel 
{ 
...... 
...... 
} 
and one Edit ViewModel 
public class EditViewModel:CreateViewModel{ 
    public string AdditionalProperty1{get;set;} 
    public string AdditionalProperty2{get;set;} 
} 

,並在您的視圖,你可以這樣做:

<%:if(Model.GetType().Name.ToString() == "EditViewModel"){%> 
    <%:Html.Textbox("AdditionalProperty1")%> 
    <%:Html.Textbox("AdditionalProperty1")%> 
<%}> 

有一個價格動態支付。你鬆散intellisense,你不能使用強類型的幫手(至少在asp.net MVC 2)。

+0

難道我不會將它轉換爲EditViewModel並查看它是否轉換它然後使用強類型幫助器?我會試試這個東西,看看會發生什麼。我想如果編輯和添加完全不同的然後雅我會做出不同的意見,但我可以他們是80至90%類似,那麼我沒有看到那裏點。我的意思是他們可能會告訴你重構你的代碼,如果你試圖爲你的服務器端代碼做到這一點。 – chobo2 2011-04-17 19:10:42

+0

我不知道,但我懷疑這是可能的。因爲如果你知道編譯時的類型,就沒有意義使它變成動態的 – 2011-04-17 19:47:57

+0

好吧我想通了所有這些。看我的編輯 – chobo2 2011-04-17 22:56:41