tags:

views:

31

answers:

1

Hi,

I'm not sure what I am doing wrong here, not even sure if I am on the right track. I have a view model and I create a drop down list from it. Here is my view model:

public class ApplicationViewModel
   {
      public Application Application  { get; private set; }
      public SelectList AccountTypes { get; private set; }

      public ApplicationViewModel(Application application, IEnumerable<AccountType> accountTypes)
      {
         Application = application;
         AccountTypes = new SelectList(accountTypes, "AccountTypeID", "AccountTypeName", application.AccountTypeID);
      }
   }

Here is my Create (get) action:

public ActionResult Create()
      {
         var viewModel = new ApplicationViewModel(new Application(), db.AccountTypes);

         return View(viewModel);
      }

And my view code:

<%: Html.DropDownListFor(???, Model.AccountTypes, "-- Select --") %>
               <%: Html.ValidationMessageFor(???) %>

In the code above, I'm not exactly sure what must come in ??? The initial value is "-- Select --". If the user clicks on the submit button and the dropdown's value is still "-- Select --" then it must display a message.

I am also using EF4. Please can someone advise as to what to do. Code samples would be appreciated.

Thanks.

+2  A: 

If your View is strongly typed ie:

Inherits="System.Web.Mvc.ViewUserControl<Model.NameSpace.ApplicationViewModel>"

Then the ??? in your view code should be a lambda expression referring to the items in your ViewModel. (I assume your ViewModel's Application object has a property that is going to be assigned a value based on the drop down list?)

I've assumed your application object has an AccountType property, For example:

??? should be something like:

<%= Html.DropDownListFor(x => x.Application.AccountType, Model.AccountTypes) %>

The value from the drop down list will populate the AccountType property on your Application model and will be populated with the AccountTypes from your ViewModel.

Hope this helps.

-- EDIT --

On your Application model, use the namespace:

using System.ComponentModel.DataAnnotations;

Above your AccountTypes property, add

[Required(ErrorMessage="Account Type Required")]

I think this should work.

James
Thanks for the answer. Yes it is a strongly typed view. It populates correctly your way, but I'm not getting the Html.ValidationMessageFor to trigger if nothing was selected. I tried Html.ValidationMessageFor(m => m.Application.AccountType) but it is not working.
Brendan Vogt
Thanks it works now :)
Brendan Vogt
Not sure if I can ask this here, when I click on submit then my Application does not have the AccountType or AccountTypeID. Here is my Create action: public ActionResult Create(Application application). How does this get set?
Brendan Vogt