Search code examples
c#razorentity-framework-6asp.net-mvc-viewmodelasp.net-mvc-5.1

How to select an existing object for a required relationship in MVC?


My domain classes:

public class Site
{
    [Key]
    public virtual int SiteId { get; set; }
    public virtual Address Address { get; set; } // Required
}

public class Address
{
    [Key]
    public virtual int AddressId { get; set; }
}

SiteCreate View contains only the following textbox:

@Html.EditorFor(model => model.SiteId)

When I PostBack, an exception is thrown, as indicated below in SiteController:

[HttpPost]
public ActionResult Create([Bind(Include="SiteId,Name")] Site site)
{
    if (ModelState.IsValid)
    {
        db.Sites.Add(site);
        db.SaveChanges(); // ***Error Here***!!!
        return RedirectToAction("Index");
    }
        return View(site);
}

It is obvious that exception is due to missing required "Address" object.

I want to select an existing "Address" object and include it in "Site" entity.

I have used a JQuery dialog box in my View to select an existing "AddressId" from the database.

My question is how to plug that "Address" object to "Site" in my View? Or else pass it to the controller and plug it to "Site" entity?

Please Help. Thanks!


Solution

  • MVC is going to be looking for an input element with the name attribute set to Address.AddressId when it attempts to rebuild your model.

    Add

    <input type="hidden" name="Address.AddressId" value="" id="address" />
    

    or

    @Html.HiddenFor(m => m.Address.AddressId, new { @id="address"})
    

    to your form, then set it's value to whatever you need via jQuery.

    An easy way to ensure you have the correct syntax for model binding is to simply add an EditorFor(m => m.Address.AddressId) and then checking what it generates for the name attribute on that input element