public class EntryViewModel : BaseViewModel { // The actual binding entity - doesn't have to be an entitiy // could also be individual values. There could be more than one here public Entry Entry {get; set; } // inherited from my BaseViewModel public ErrorDisplay ErrorDisplay {get; set; } // object that renders errors public string ErrorMessage {get; set; } // single error messages public UserState UserState {get; set; } // Logon information public int Id {get; set; } }The point of the ViewModel is that it gives a top level object so you can bind multiple entities or any number of values that don't directly map to your business layer. You can also hang off things that the View might need - for special rendering operations, or for validations etc.
>> [HttpPost] >> public ActionResult Save(EntryViewModel model) >> { >> if (!ModelState.IsValid) >> { >> // Handle error and display error result >> model.ErrorDisplay.ShowError(model.ErrorDisplay.AddMessages(ModelState)) >> return View("Show"); >> } >> >> var entryBus = new busEntry(); >> >> // get entity that needs to be updated >> var entry = entryBus.Entity; >> entry.Id = model.entry.Id; >> entry.Title = model.entry.Title; >> entry.Description = model.entry.Description; >> // ... more fields to map >> >> // Or you can attach the entity - in my bus object >> // this is automatic, with EF you can use DbSet::Attach >> //entryBus.Attach(model.entry); >> >> // Validate and save the bus object >> if (!entryBus.Validate() || !entryBus.Save()) >> { >> model.ErrorDisplay.ShowError(model.ErrorDisplay.AddMessages(entryBus.ValidationErrors)); >> return View("Show"); >> } >> >> // Saved and done >> return View("Index"); >> } >>>>
>>>using System; >>>using System.Linq; >>>using System.Web.Mvc; >>>using CardNumbers.Models; >>>using CardNumbers.Data; >>> >>>namespace CardNumbers.Controllers >>>{ >>> public class ClientController : Controller >>> { >>> private IClientRepository Db; >>> >>> public ClientController() >>> { >>> this.Db = new ClientRepository(new CardNumbersContext()); >>> } >>> public ClientController(IClientRepository Db) >>> { >>> this.Db = Db; >>> }>>>
>>> [HttpPost] >>> public ActionResult Edit(int id, FormCollection collection) >>> { >>> try >>> { >>> var client = Db.GetClientById(id); >>> >>> client.Address = collection["Address"]; >>> return this.Client(collection); >>> } >>> catch >>> { >>> return View(); >>> } >>> }>>>