Dudedolf
Dudedolf

Reputation: 625

ASP.net MVC create related object using partials

I am relatively new to ASP and MVC but have got on ok so far. I am using the DB first approach and have my DB tables all setup (it is an existing DB cleaned up with FKs etc).

I have a route of FKs:

Contact
    - LettingContact
         - Landlord          
         - Tenant

I would like to be able to use partials to display the data e.g. /Contact/_Create will hold the Contact info i.e. Title, Forename, Surname and will be used both by /Contact/Create and /Tenant/Create. I managed to get it working not using the partials and just using the field on the Tenant/Create html form and showing the relevant data from the models. To the Tenant/Create in the controller i did the following (doing the following stopped me getting null exceptions in the partial)

Tenant tenant = new Tenant();
LettingsContact lettingsContact = new LettingsContact();
Contact contact = new Contact();
tenant.LettingsContact = letContact;
tenant.LettingsContact.Contact = contact;
return View(tenant)

Now the View is

//using Html.BeginForm etc

@{
   Html.RenderPartial("../Contact/_Create", Model.LettingsContact.Contact);
   Html.RenderPartial("_Create", Model);
}


<input type="submit" value="create">

//rest of html

Now when I click the submit button it goes to my /Tenant/Create post event.

[HttpPost]
public ActionResult Create(Tenant  tenant)
{
     if (ModelState.IsValue)
     {
         tenant.ContactID = Guid.NewGuid();
         tenant.LettingsContact.Contact.ContactID = tenant.ContactID;
         db.Tenants.AddObject(tenant);
         db.SaveChanges();
         return RedirectToAction("Index");             
     }
}

However the line which reads tenant.LettingContact.Contact.ContactID crashes will a NullReferenceException to the LettingsContact is null. Any reason why the partials are not maintaining the Models?

Also if there is a better way of doing this please let me know as this is still very new to me.

The reason I want to use partials is that it will enable me to reuse the forms in jQuery modal forms etc.

Upvotes: 1

Views: 315

Answers (1)

stijndepestel
stijndepestel

Reputation: 3564

If you want a form to post back information that you don't want displayed on the page you should use a hidden field. Have a look at Html.Hidden() and Html.HiddenFor().

Hidden on msdn: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.hidden.aspx

HiddenFor on msdn: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.hiddenfor.aspx

Upvotes: 1

Related Questions