1

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>
0

1 Answer 1

4

Try @Model.objName with an uppercase 'M'. The lower case model is the "type" expected from controller. Model is the instance of the "type" passed.

Sign up to request clarification or add additional context in comments.

3 Comments

That got it, thank you! Why does my intellisense not support "Model"? It shows "ModelBinders" etc, but there is no option for "Model"
Try closing out of VS 2013, reopen the project, and see if that helps. I have had that happen in 2013 just recently and it helped me.
Weird, that's what it was. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.