2011-04-17 164 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