我有一個包含我的表單輸入(文本框)的局部視圖。我有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中並將其轉換回您的底座。那麼你將擁有所有的財產,因爲它似乎工作
您可以在每個視圖中顯示所需的字段。你如何在意見上建立表格? – tomasmcguinness 2011-04-17 17:35:47
@tomasmcguinness - 我想避免重複的數據。我的意思是我不想複製10個字段,因爲我有2個字段需要添加。 – chobo2 2011-04-17 18:13:29