I\'m new to ASP.NET MVC and I want to create a view where I can create a new object along with the related objects.
As example: I have the following class Person:
I would suggest you the following approach:
1.Create a view models:
public class AddressViewModel
{
public string City { get; set; }
public string Street { get; set; }
}
public class PersonViewModel()
{
public string FirstName { get; set; }
public string LastName { get; set; }
public AddressViewModel AddressViewModelTemplate {get; set;}
public Collection Addresses {get; set;}
}
Then in your view you can use hidden EditorTempalete for the AddressViewModelTemplate
, and show it with javascript on some button click. Of course, you will have to adjust the names of the generated collection for the binding.
Sample Editor Template. You can choose better structure.
@model AddressViewModel
@Html.LabelFor(x => x.City)
@Html.TextBoxFor(x => x.City)
@Html.LabelFor(x => x.Street)
@Html.TextBoxFor(x => x.Street)
The in your strongly typed View:
@model PersonViewModel;
@using(Html.BeginForm())
{
//Display textbox for Person properties here
....
@Html.EditorFor(x => x.AddressViewModelTemplate)
....
}
讨论(0)