I am a real beginner at ASP.NET and working with MVC2 + EF4 in Visual Studio 2010.
I am trying to use the MVVM pattern and strongly typing my View to a ViewModel.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="True" CodeBehind="~/Views/Options/Index.aspx.cs" Inherits="System.Web.Mvc.ViewPage<OptionsViewModel>" %>
My OptionsViewModel looks like this:
public class OptionsViewModel
{
public List<DeskPreference> DeskPreferences { get; set; }
public List<DayPreference> DayPreferences { get; set; }
}
In the controller I create a new OptionsViewModel and do return View(myOptionsViewModel);
Then, for example, I want to check/uncheck some boxes based on what is in DayPreference. I don’t get how to access the model from my code behind file, which looks like this:
using System.Web.Mvc;
using DeskRota_v1.ViewModels;
public class OptionsPage : System.Web.Mvc.ViewPage<OptionsViewModel>
{
protected void Page_Load(object sender, EventArgs e)
{
setCheckBoxes();
}
private void setCheckBoxes()
{
foreach (DayPreference dayPreference in Model.DayPreferences)
{
\\ check boxes here
}
}
It comes up with “The name ‘Model’ does not exist in the current context”. Also if I try to do <% Model. %> in the view there is no intellisense, which I thought there should be. Could somebody please explain what I am doing wrong? How am I supposed to access the ViewModel and its properties?
Your controller will have two overloads of each action method for each view that you need to post back: one with an HttpGet signature and one with an HttpPost signature. The GET version will be called on the first load of the page and will set the initial page values.
The POST version will be called on form submit and accept your viewmodel as an arg. MVC will automagically reconstruct it with the values that were posted in your form (assuming you’re using relatively simple types. More complex types is doable but more complicated).
My own convention is to have a work unit in the ViewModel that is responsible for persisting or otherwise processing the values that were submitted. Do NOT put this sort of thing in the controller.
Your viewmodel will need a parameterless constructor, which is the version MVC will use when reconstituting it on page submit. In general I also have a second constructor I use on the GET version so that the VM can instantiate it’s initial values.