Askert
Askert

Reputation: 11

Save data in 2 tables mvc

My project is Room-reservation service .I have View :

@model Client

@using (Html.BeginForm("SaveUserDB", "Booking", FormMethod.Post))
                {
<div class="editor-label">
     @Html.Label("Surname")
     @Html.TextBoxFor(model => model.Surname)
</div>
<div class="editor-label">
     @Html.Label("Name")
     @Html.TextBoxFor(model => model.Name)
     @Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
     @Html.Label("Patronymic")
     @Html.TextBoxFor(model => model.Patronymic)
</div>
<input type="submit" id="submit" value="Reservation" />

And I have controller for this View:

[HttpPost]
public ActionResult SaveUserDB(Client client)
{
    if (ModelState.IsValid)
    {
        using (db)
        {
            db.Client.Add(client);
            db.SaveChanges();
            return RedirectToAction("Thankyou");
        }
    }

    return View(client);
}

This controller save data client to database table Client. But I need also create record in second table Reservation, which takes parameters: Datetime.Now , and Client.Id. Parameter Client Id in database is autoincrement, but doesn't display in the View.

Upvotes: 1

Views: 567

Answers (1)

David
David

Reputation: 219096

Well, if this is how you add a record to the Client table:

db.Client.Add(client);

Then why not use that same exact approach to add a record to the Reservation table? Something like this:

var reservation = new Reservation
{
    ClientID = client.ID,
    SomeOtherColumn = DateTime.Now
};
db.Reservation.Add(reservation);

(Note: This is based on speculation of what your Reservation object/table might look like based on your description. But the concept is the same. Create an instance of a reservation object and add it to the data context.)

Upvotes: 1

Related Questions