Ryan
Ryan

Reputation: 85

How do you pass an object from the model to the view while specifying which variable of the object?

So I am pretty fresh to .NET, c#, and MVC.

The issue I am having is that I have created an Employee object in my home controller under my Index():

public ActionResult Index(string Name, string ID, decimal? HourlyPayRate, int? HoursWorked)
    {
        var Emp = new Employee(Name, ID);

        if(Name == null || ID == null || !HourlyPayRate.HasValue || !HoursWorked.HasValue)
        {
            return HttpNotFound();
        }
        else
        {
            return View(Emp);
        }    
    }

I am wanting to pass my View the Employee's Name to display as the title. Here is my current view:

@model Practice.Models.Employee

@{
ViewBag.Title = ;
}

<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

I'm not sure if I'm just not calling the correct thing with @model (still kinda fuzzy on how all of that works) or if I just don't understand the syntax for calling an object.

Upvotes: 0

Views: 32

Answers (1)

marco
marco

Reputation: 667

In Razor, you can just write

<p>Employee is: @Model.Name</p>
..

Or in your case

ViewBag.Title = Model.Name

The rest looks ok to me.

Upvotes: 2

Related Questions