【问题标题】:pass a model generated using automapper to Html.editorformodel()将使用 automapper 生成的模型传递给 Html.editorformodel()
【发布时间】:2014-02-13 06:37:42
【问题描述】:

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

人员:姓名、地址、address1、cityid、stateid、countryid、pincode、..
公司:名称、地址、address1、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 以便自动映射器可以提取所有数据)

和 /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");,但这会引发错误
“System.InvalidOperationException:传递到字典的模型项的类型为“CustomerModel”,但该字典需要“AddressModel”类型的模型项”。
在这种情况下,我不知道如何将自动映射器生成的地址模型传递给编辑器模板。

我不能使用部分视图,因为在这种情况下我希望地址字段以 basicInfo 为前缀,而在另一种情况下我不需要任何前缀。

这几天让我发疯。请帮忙!!!

【问题讨论】:

    标签: c# asp.net-mvc editortemplates


    【解决方案1】:

    【讨论】:

    • 成功了!我将 PersonModel 更改为 public string LastName {get;set;} public string Email {get;set;} public long Phone {get;set;} public AddressModel addressModel {get;set;}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2014-06-26
    • 2015-10-23
    • 2023-03-03
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多