views:

33

answers:

3

Newbie-ish questions ahead:

Where should I put my View Model declarations?

I created a file called "ViewModels.cs" in my Models folder. I created a few View Model classes, including one called RatingViewModel:

using System;
using System.Collections.Generic;var
using System.Linq;
using System.Web;

namespace Web.Model
{
public class ViewModels
{

    public class RatingViewModel
    {
        public User Rater { get; set; }
        public Rating Rating { get; set; }
    }

}

}V

Now I'm trying to create a helper/service class function that returns a new RatingViewModel object.

I created a "RatingsHelpers.cs" file. But when I try to crate a new RatingViewModel object, it has no idea what I'm talking about. I can't figure it out. Am I missing some reference? How can I create/return a new View Model object from my helper/service class?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Web.Model;

namespace System.Web.Mvc
{
    public static class RatingsHelpers
    { 
        public static RatingViewModel functionname()
        { ..... }

But it doesn't know what "RatingViewModel" is...!?!?!?

I just know this should be obvious.

Pulling my hair out,

Johnny

+2  A: 

The problem is that you put the RatingViewModel class inside the ViewModels class, which means that it's a child class of ViewModels. I'm not sure that's the behaviour you want. If you want to call a child class you have to write ViewModels.RatingViewModel to reference the class.

scripni
+2  A: 

Expanding on what scripni said. Having a RatingViewModel class nested inside a ViewModels class inside the Web.Models seems superfluous. You probably want to get rid of the outer ViewModels class.

Mike
+2  A: 

To sum up:

  1. You've created a ViewModels class inside the Web.Model namespace. This class declares a nested class called RatingViewModel
  2. Inside the helper RatingsHelpers located in the System.Web.Mvc namespace you are trying to access the RatingViewModel class.

You could achieve this by using ViewModels.RatingViewModel but I wouldn't recommend you doing so. Nesting classes like this makes no sense.

Instead you could place each view model class into a separate .cs file and put it directly into the Web.Model namespace:

namespace Web.Model
{
    public class RatingViewModel
    {
        public User Rater { get; set; }
        public Rating Rating { get; set; }
    }
}

Then inside the helper class use could use directly the RatingViewModel class.

Darin Dimitrov
Thank you very much!
johnnycakes