ASP .NET MVC 5 - Customer-Address One-To-One relationship

核能气质少年 提交于 2019-12-12 12:55:36

问题


I've looked into forums here and actually found some similar questions, but not the same ones. Similar solutions did not give me the right answer.

I'm working with ASP .NET MVC 5 using Entity Framework and Code First approach.

I would like to model Customer -> Address One-To-One relationship. What I've modeled is:

Customer class

public class Customer
{
    public int Id { get; set; }

    public string Name { get; set; }

    [DisplayName("Middle Name")]
    public string MiddleName { get; set; }

    [DisplayName("Last Name")]
    public string LastName { get; set; }


    public int AddressId { get; set; }

    public virtual Address Address { get; set; }
}

Address class

public class Address
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Country { get; set; }

    public string City { get; set; }

    public string PostalCode { get; set; }

    public string Street { get; set; }

    public string HouseNumber { get; set; }

}

Having this relation modeled scaffolding mechanism gives the following (examples for Create methods):

Customer controller Create method

 // GET: Customers/Create
    public ActionResult Create()
    {
        ViewBag.AddressId = new SelectList(db.Addresses, "Id", "Name");
        return View();
    }

    // POST: Customers/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Name,MiddleName,LastName,AddressId")] Customer customer)
    {
        if (ModelState.IsValid)
        {
            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.AddressId = new SelectList(db.Addresses, "Id", "Name", customer.AddressId);
        return View(customer);
    }

Customer view Create file

@model Models.Customer

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Customer</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.MiddleName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MiddleName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AddressId, "AddressId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("AddressId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.AddressId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

The result I have now: a Create view with fields for all Customer's data and a DropDown list with already existing Addresses in the database to choose for newly created Customer.

Expected result: a Create view with fields for Customer's data and all Address's fields for the user to fill. When saving the Customer, new Address entity should be saved and assigned for newly created Customer.

How is the best to achieve that? I know I can access my Customer's Address's fields in the view by simply doing model.Address.Name for instance, but how can I post it then to the controller and save into database?

Thank you in advance!


回答1:


You should not let user to enter Id of adress which you are creating. Id should be set by database. (This should be a comment but my level of reputation does not allow me comment above).



来源:https://stackoverflow.com/questions/33880723/asp-net-mvc-5-customer-address-one-to-one-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!