The controller;
[Authorize(Roles = "Inputter")]
[HttpPost]
public ActionResult Edit(int contractId, FormCollection formValues)
{
if (ModelState.IsValid)
{
using (var db = new ITOCEntities())
{
var contract = db.Contracts.Single(x => x.ContractId == contractId);
string letter = contract.ContractNo_Letter;
UpdateModel(contract, "Contracts", formValues);
if (contract.ContractNo_Letter != letter)
contract.ContractNo_Number = Contract.AutogenerateContractNumber(contract.ContractNo_Letter);
var clientContact = db.Contacts.Single(x => x.ContactId == contract.ClientContactId);
UpdateModel(clientContact, "Contact", formValues);
var contractAdministrationContact =
db.Contacts.Single(x => x.ContactId == contract.ContractAdministratorContactId);
UpdateModel(contractAdministrationContact, "Contact", formValues);
db.SaveChanges();
}
return RedirectToAction("List");
}
return View();
}
------------------------------------------------------------
The ViewModel
public class ContractViewModel
{
//private ITOCEntities db = new ITOCEntities();
public Contract contract { get; set; }
public IList<ContractType> contractTypes { get; set; }
public IEnumerable<SelectListItem> contractTypesSelectList
{
get
{
return this.contractTypes.Select(item => new SelectListItem
{
Text = item.ContractType1,
Value = item.ContractTypeId.ToString()
});
}
}
public Contact clientContact { get; set; }
public Contact contractAdministratorContact { get; set; }
public ContractViewModel()
{
using (var db = new ITOCEntities())
{
this.contractTypes = db.ContractTypes.ToList();
this.clientContact = new Contact();
this.contractAdministratorContact = new Contact();
this.clientContact.ContactTypeId =
db.ContactTypes.Where(x => x.ContactType1 == "Client").SingleOrDefault().ContactTypeId;
this.contractAdministratorContact.ContactTypeId =
db.ContactTypes.Where(x => x.ContactType1 == "CA").SingleOrDefault().ContactTypeId;
}
}
public ContractViewModel(int contractId)
{
using (var db = new ITOCEntities())
{
this.contractTypes = db.ContractTypes.ToList();
this.contract = db.Contracts.Where(x => x.ContractId == contractId).SingleOrDefault();
this.clientContact =
db.Contacts.Where(x => x.ContactId == this.contract.ClientContactId).SingleOrDefault();
this.contractAdministratorContact =
db.Contacts.Where(x => x.ContactId == this.contract.ContractAdministratorContactId).SingleOrDefault();
}
}
--------------------------------------------------------
The ViewModel reference in the view;
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<ITOC.WebUI.Models.ContractViewModel>" %>
|