Reputation: 1487
I am trying to create a ViewModel class. After I created class in "ViewModels" folder. My List type declaration are not recognized. My questions and code is below:
Can someone please tell me what I have missed thanks -P
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication8.ViewModels
{
//compiler does not recongize List class or SelectListitem
private List<SelectListItem> _products = new List<SelectListItem>();
//compiler does not recongize List class
public List<SelectListItem> products
{
get { return _products; }
}
}
Upvotes: 0
Views: 2330
Reputation: 3528
add a class definition under Models folder, i.e:
namespace MvcApplication1.Models
{
public class WhateverNameYouWantModel
{
public string Foo { get; set; }
public string Bar { get; set; }
}
}
right click on Controllers folder and add a new controller. the name must end with "Controller". don't bother checking option to add action methods. the controller would look like this:
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HelloController : Controller
{
public ActionResult Index()
{
return View(new WhateverNameYouWantModel());
}
}
}
right click on the Index() signature above and choose "Add View". Make sure nothing is checked, the view name matches the action name "Index" and Razor is the engine. add the model type at the top:
@model MvcApplication1.Models.WhateverNameYouWantModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>hello world!</div>
</body>
</html>
set the mvc project as your startup project, press F5, the browser will open to http://localhost:xxxx now you will need to point to http://localhost:xxxx/Hello/Index
In asp.net mvc names are everything between the views, actions and controllers. Its all convention, you don't need to stick to it but if you don't you are gonna have to do some extra plumbing.
Upvotes: 2
Reputation: 73123
Are there some special way of creating ViewModel Classes?
No, create them like creating any other class. The convention is to place them in the Models folder.
Are ViewModels a methodology, rather than a feature in MVC3?
Kind of. They're not a feature of the framework itself, but a recommendation to keep your View's simple and clean, and simplify model binding.
Can someone please tell me what I have missed thanks
Where's your class declaration?
namespace MvcApplication8.ViewModels
{
public class ThisIsTheClassNameAndMustGoFirst
Upvotes: 4