Question:
How do I pull a simple model into a view as a strongly-typed object, using a controller?
Problem:
I create a simple class in a model, newObject. That class is referenced and passed to the view by my controller. However, I can't access the class in the view, using the Razor @model statement.
Details:
I'm a beginner learning ASP.NET and C#. I'm using Visual Studio 2013 Express on a Win7 machine. I started with an empty project, with folders and core references for MVC.
In short, I'm trying to get a handle on learning by doing.
I've followed some tutorials on www.asp.net, but I'm trying to learn bare bones, without entity framework and that sort of thing.
Code:
Here's my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class MyObject
{
public string objName = "Object1", objType = "Type1";
}
}
The controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
MyObject newObject = new MyObject();
return View(newObject);
}
}
}
and, the View. I can't access newObject in the view for some reason:
@model WebApplication1.Models.MyObject
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
This is a test page.<br />
<!--Error on the next line-->
@model.objName
</div>
</body>
</html>