Kashif
Kashif

Reputation: 3034

Save two Entities from one View

enter image description hereHow to save two Entities from one View. Suppose I have two Entities Party and Person with One to Many relation. Now I need to save both Entities from Party View. I am using ASP.NET MVC4.

public partial class Cm_Opt_Pty_Party_S
{
    public Cm_Opt_Pty_Party_S()
    {
        this.Cm_Opt_Psn_Person_S = new HashSet<Cm_Opt_Psn_Person_S>();
    }

    public int Pty_ID { get; set; }
    public Nullable<int> Pty_PARTYTYPECODE { get; set; }
    public string Pty_FULLNAME { get; set; }
    public string Pty_GOVTID { get; set; }
    public Nullable<int> Pty_GOVTIDTC { get; set; }
    public Nullable<int> Pty_GOVTIDSTAT { get; set; }

    public virtual ICollection<Cm_Opt_Psn_Person_S> Cm_Opt_Psn_Person_S { get; set; }
}

Upvotes: 0

Views: 198

Answers (2)

Lotok
Lotok

Reputation: 4607

I have a better understanding of your issue, so editing this answer to show the solution I would use.

Your Controller will deliver the Party object to your view for displaying the Party information. Using a loop you can display the items contained in the collection.

@foreach(var m in Model.Persons)
{
    @Html.DisplayFor(model=>m.FirstName)
    @Html.DisplayFor(model=>m.Surname)
}

When you want to add more items into the collection, you will need to render a partial view or new view containing a form for adding a Person. It will be strongly typed as Person model and the Controller action recieving the post will be expecting a Person

If for example a Person just had a FirstName,Surname and PartyId the form would use these helpers in your view

@Html.TextboxFor(m=>m.FirstName)
@Html.TextboxFor(m=>m.Surname)
@Html.TextBoxFor(m=>m.PartyId)

You then submit that back to your controller, and have logic for adding the person to the collection. Then return the view with Party model containing the newly added Person in the Persons collection.

Using @Ajax.BeginForm or some custom Jquery/Javascript you could handle this async to prevent page refreshing during the process.

If you don't want to do it this way, another option is EditorTemplates. See here for example: ASP.NET MVC LIST and Create in same view

Upvotes: 1

ywm
ywm

Reputation: 1127

What you can do is create a ViewModel This class would contain the relevant properties needed to create both entities.

Then you base your View on the ViewModel instead, and pass that to the controller.

When you want to save the entities, you can build up the separate entities and save them.

Upvotes: 1

Related Questions