我有一个包含我的表单输入(文本框)的局部视图。我有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