将使用automapper生成的模型传递给Html.editorformodel()

时间:2014-02-13 06:37:42

标签: c# asp.net-mvc editortemplates

我有多个表在我的数据库中有地址字段。 例如:

  

人:姓名,地址,地址1,cityid,stateid,countryid,pincode,..   公司:姓名,地址,地址1,cityid,stateid,countryid,pincode,..   ..

相关的视图模型:

public class customermodel{
    public PersonModel basicInfo {get;set;}
    public string type {get;set;}
    public long id {get;set;}
    ...
}
public class PersonModel{
    public string FirstName {get;set;}
    public string MiddleName {get;set;}
    public string LastName {get;set;}
    public string Email {get;set;}
    public long Phone {get;set;}
    public string address {get;set;}
    public string address1 {get;set;}
    public long cityid {get;set;}
    public long stateid {get;set;}
    public long countryid{get;set;}
    public long pincode {get;set;}
}

我为地址创建了一个类:

public class AddressModel{
    public string address {get;set;}
    public string address1 {get;set;}
    public long cityid {get;set;}
    public long stateid {get;set;}
    public long countryid{get;set;}
    public long pincode {get;set;}
}

(注意:我没有在personmodel中使用AddressModel,因此automapper可以提取所有数据)

并在/Views/Shared/EditorTemplates/AddressModel.ascx中对editortemplate进行相同操作

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AddressModel>" %>

<%: Html.TextBoxFor(model => model.address, new { Placeholder = "Country" })%>
<%: Html.TextBoxFor(model => model.address1, new { Placeholder = "State", style="display:none;" })%>
...

从我的EditCustomer视图中,我想调用地址模型的编辑器模板。

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CustomerModel>" %>

<%: Html.TextBoxFor(model => model.id) %>
<%: Html.TextBoxFor(model => model.type) %>
<%: Html.EditorFor(model => (AddressModel)AutoMapper.Mapper.DynamicMap<AddressModel>(model.personModel), "AddressModel")%>
...

现在我收到了EditorFor行的以下错误:
模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。

我想使用Html.EditorForModel("AddressModel");,但这会引发错误 &#34; System.InvalidOperationException:传入字典的模型项的类型为&#39; CustomerModel&#39;,但此字典需要类型为&#39; AddressModel&#39;的模型项。 &#34;
在这种情况下,我不知道如何将automapper生成的addressmodel传递给editortemplate。

我无法使用partialViews,因为在这种情况下我希望地址字段以basicInfo为前缀,而在另一种情况下我不需要任何前缀。

这让我疯狂了几天。请帮忙!!!

1 个答案:

答案 0 :(得分:0)

相关问题