I'm new to MVC5 and just trying to grasp the use of ViewModels. My questions is if I have to instantiate my model class in my the controller of my ViewModel. I'm making a database to organize bills, and have a Cash model that maps to a database table, and a CashViewModel to view/edit the data.
Here is my model:
public class Cash
{
public int CashId { get; set; }
public decimal CashAmount { get; set; }
public int CashTypeId { get; set; }
public DateTime DateModified { get; set; }
public CashType CashType { get; set; }
}
Here is my ViewModel:
public class CashViewModel
{
public int CashId { get; set; }
public decimal CashAmount { get; set; }
public int CashTypeId { get; set; }
public SelectList CashTypeSelectList { get; set; }
}
Here is my controller:
public ActionResult Create([Bind(Include = "CashAmount,CashTypeId")] CashViewModel cashVM)
{
if (ModelState.IsValid)
{
var cash = db.Cashes.Create();
cash.DateModified = DateTime.Now;
cash.CashAmount = cashVM.CashAmount;
cash.CashTypeId = cashVM.CashTypeId;
db.Cashes.Add(cash);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CashTypeId = new SelectList(db.CashTypes, "CashTypeId", "CashTypeName", cashVM.CashTypeId);
return View(cashVM);
}
I'm creating an instance of the Cash model and mapping my ViewModel class to my model class. Is this correct? When I start doing projects where there are several Models with several attributes in one ViewModel, this seems like it will get out of hand quickly.
All the questions and articles I read are either too vague or too detailed and I can't find anything to my specific question, sorry if there is something already out there.