I'm new to .NET together, be patient with me if I get any stupid mistakes.
I am using ASP.NET MVC 3 with .NET 4.0
I want to have a Create view for a model with a child model. This view should include the partial Create model, I will use the following simple example to illustrate:
Person Model
class Person { public string Name { get; set; } public Address { get; set; } }
Model Address
class Address { public string City { get; set; } public string Zip { get; set; }
Controller Actions
class MyController : Controller { public ViewResult Create() { var person = new Person(); var address = new Address();
The view hierarchy I want to have:

The solutions I tried to achieve this are as follows:
First approach: use @Html.Partial(..) or @{Html.RenderPartial(..)}
What I've done:
Person view
@model Person @using(Html.BeginForm()){ @Html.EditorFor(m=>m.Name) @Html.Partial(MyViews.AddressPartialView, @Model.Address) }
Partial View Address
@model Address @Html.EditorFor(m=>m.Zip) @Html.DropDownListFor(m=>m.City, @Model.CityDropDown)
Problem:
When the form is person.Address is null. After a short search on Google, I found out that in order to send an address field, the generated HTML markup should be as follows (note the Address_ prefix):
<form...> <input type=text id="Name" /> <input type=text id="Address_Zip" /> <select id="Address_City"> </select> </form>
Needless to say, the generated HTML markup does not match in my case, but instead (the Address_ prefix Address_ missing):
<form...> <input type=text id="Name" /> <input type=text id="Zip" /> <select id="City"> </select> </form>
Second approach: using the EditorTemplate for the Address model
What I've done:
I moved the partial view Address to the View / Shared / EditorTemplates folder , indicating that it has the same name as the Address property in Person , i.e. Address.cshtml .
Person view
@model Person @using(Html.BeginForm()){ @Html.EditorFor(m=>m.Name) @Html.EditorFor(@Model.Address)
Problem:
Using this approach, the generated markup is actually the proper prefix (i.e. Address_ ), but I get an Object link not set to exclude the instance for the Address.CityDropDown property, which tells me that the pre-initialized address object in the controller action for what - Either the reason is not transferred to a partial view.
Third approach: put all the Address fields in the Person model
This approach works without problems, but I do not want to use it, because I do not want to have redundant code if I ever want to create a view representation for an address in another model.
Summarizing
What should I do to have a partial reusable creation that I can use in my application?
source share