Question

I have multiple tables that have address fields in my database. ex:

Person: name, address, address1, cityid, stateid, countryid, pincode, ..
Company: name, address, address1, cityid, stateid, countryid, pincode, ..
..

Relevant viewmodels:

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;}
}

I created a class for address:

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;}
}

(NOTE: I did not use AddressModel in personmodel so that automapper can pull in all the data)

and editortemplate for the same in /Views/Shared/EditorTemplates/AddressModel.ascx

<%@ 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;" })%>
...

From my EditCustomer view, I want to call the editor template for address model.

<%@ 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")%>
...

Now I get the following error for the EditorFor line:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

I want to use Html.EditorForModel("AddressModel");, but that throws me an error
"System.InvalidOperationException: The model item passed into the dictionary is of type 'CustomerModel', but this dictionary requires a model item of type 'AddressModel'".
I dont know how to pass the automapper generated addressmodel to the editortemplate in this case.

I cant use partialViews because I want the address fields to be prefixed with basicInfo in this case and I dont need any prefix in another case.

This is driving me crazy for a couple of days. Please help!!!

Was it helpful?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top