Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.net MVC create related object using partials
    primarykey
    data
    text
    <p>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).</p> <p>I have a route of FKs:</p> <pre><code>Contact - LettingContact - Landlord - Tenant </code></pre> <p>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)</p> <pre class="lang-default prettyprint-override"><code>Tenant tenant = new Tenant(); LettingsContact lettingsContact = new LettingsContact(); Contact contact = new Contact(); tenant.LettingsContact = letContact; tenant.LettingsContact.Contact = contact; return View(tenant) </code></pre> <p>Now the View is</p> <pre><code>//using Html.BeginForm etc @{ Html.RenderPartial("../Contact/_Create", Model.LettingsContact.Contact); Html.RenderPartial("_Create", Model); } &lt;input type="submit" value="create"&gt; //rest of html </code></pre> <p>Now when I click the submit button it goes to my /Tenant/Create post event.</p> <pre><code>[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"); } } </code></pre> <p>However the line which reads <code>tenant.LettingContact.Contact.ContactID</code> crashes will a NullReferenceException to the LettingsContact is null. Any reason why the partials are not maintaining the Models?</p> <p>Also if there is a better way of doing this please let me know as this is still very new to me. </p> <p>The reason I want to use partials is that it will enable me to reuse the forms in jQuery modal forms etc.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload