Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing model properties in Razor-4 view

I have the following EF generated data model:

public partial class PrinterMapping
{
    public string MTPrinterID { get; set; }
    public string NTPrinterID { get; set; }
    public string Active { get; set; }
}

I then have the following view model:

public class PrinterViewModel
{
    public PrinterMapping PrinterMapping;
    public Exceptions Exceptions;
    public IEnumerable<PrinterMapping> Printers;
}

In my Index Action in HomeController I am passing my view model to the Index view.

private eFormsEntities db = new eFormsEntities();
public ActionResult Index()
{
    PrinterViewModel printerModel = new PrinterViewModel();
    printerModel.Printers = from pt in db.PrinterMapping select pt;

    return View(printerModel);
}

My Index view is calling a partial view in the following manner towards the end (probably wrong):

@Html.Partial("~/Views/Home/GridView.cshtml")

My GridView.cshtml looks like:

@model AccessPrinterMapping.Models.PrinterViewModel

<h2> This is Where the Grid Will Show</h2>

@{
    new WebGrid(@model.Printers, "");
}

@grid.GetHtml()

I learned about the WebGrid method from http://msdn.microsoft.com/en-us/magazine/hh288075.aspx.

My WebGrid line isn't happy at all since it doesn't recognize @model within that line. How do I access the Printers in the view model that I passed in? Is this even possible?

Thanks very much to you all.

like image 920
user3041439 Avatar asked Dec 04 '13 09:12

user3041439


People also ask

How do I access model value in view?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.


1 Answers

Theres two issues with your code.

First, you should explicitly pass your model in like this:

 @Html.Partial("~/Views/Home/GridView.cshtml", Model) @* explicitly pass the model in *@

Then, because you are already in a code block in your partial view.. you don't need the @ symbol.. and Model has an uppercase M.

 new WebGrid(Model.Printers, "");

@model is a directive for your views/partial views. Think of it as a "configuration" command. Model is an actual property. It is the object that is passed into the view.. and is of the type you specified with the @model directive.

like image 71
Simon Whitehead Avatar answered Sep 20 '22 12:09

Simon Whitehead