Question

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!

Était-ce utile?

La 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

Autres conseils

Well, one way or another, you'll need to put it into a hidden <input /> element. I'm not familar with the details of the [Bind] attribute, but I think there's a way to name to input to say "This is the addressId of the Address of the Site". If not, just make it anouther parameter to the Create action and assign it in there.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top