I have a view with form that has data bind from model/DB with 1-to-many entites/tables.
The view references Contract class to form a contract object which has attributes: Customer ID FK, Customer virtual object, and other object's ID and virtual object related from other tables. I'm using Entity Framework.
Contract class from Model:
public partial class Contract
{
public int Contract_ID { get; set; }
public System.DateTime DateCreated { get; set; }
public string CustomerId { get; set; }
public Nullable<int> Status_ID { get; set; }
public Nullable<int> SA_ID { get; set; }
public virtual Customer Customer { get; set; }
public virtual ContractStatus ContractStatus { get; set; }
public virtual ServicesAccess ServicesAccess { get; set; }
}
I'm not using a View model, as it may introduce redundancy. Not sure how I can use a View Model too for this.
When I edit a contract via index page and save it posts a null Customer object from Contract to the HTTPPost edit method parameter. For a contract I only do not want the customer to be edited, so in the edit view I have:
@Html.HiddenFor(model => model.CustomerId)
<div class="display-field">
@Html.DisplayFor(model => model.Customer.CustomerLegalName)
So I get the customer id correctly from contract. Whereas the get Edit method does not have null Customer object. Why is this happening? This happens with ServicesAccess object too.
In the controller with edit method, to get the object to save I have to find the object by this way:
contract.ServicesAccess = db.ServicesAccesses.Find(contract.SA_ID);
If I don't do this then contract.Customer or contract.ServiceAccess is either null or initialized with null attributes. Cheers.