keeehlan
keeehlan

Reputation: 8054

MVC Views - Can't access variable passed from controller to View

I've been seeing examples like the 3rd code block in this answer whereas the ViewModel's members are being accessed via model.Member, however I have NEVER been able to use the lowercase model in any of my views.

I understand how to use the @model directive and the Model property in MVC Razor Views. What I do not understand is how model.ChartItems is accessible from within the view when I have code that is nearly identical to the example linked in the first line of my question.

I'd be grateful if somebody could clarify the difference between model.Member and Model.Member in MVC Razor views. It seems that I need to figure out how to access model.Member as shown in the link at the top of this question, but I can't seem to find any elaboration on the matter.

Here is the code for the view from which I'm trying to access model:

@model Models.StudentHistoryModel

<h2>Student History</h2>

@Html.RenderPartial("_Course", model.CourseCompletion);
@Html.RenderPartial("_Track", model.TrackCompletion);
@Html.RenderPartial("_Certification", model.CertificationCompletion);

Here is the Controller action that passes the data to the View:

public ActionResult History(int id)
{
    var history = new StudentHistoryModel();

    history.CourseCompletion = db.CourseCompletions
        .Where(c => c.StudentID == id)
        .ToList();

    history.TrackCompletion = db.TrackCompletions
        .Where(c => c.StudentID == id)
        .ToList();

    history.CertificationCompletion = db.CertificationCompletions
        .Where(c => c.StudentID == id)
        .ToList();

    return PartialView("_History", history);
}

And no, before you ask, the variable history is NOT accessible from the View.

Upvotes: 1

Views: 2010

Answers (2)

Robert Harvey
Robert Harvey

Reputation: 180777

Try this:

@model Models.StudentHistoryModel

<h2>Student History</h2>

@Html.RenderPartial("_Course", Model.CourseCompletion);
@Html.RenderPartial("_Track", Model.TrackCompletion);
@Html.RenderPartial("_Certification", Model.CertificationCompletion);

Note the use of Model, rather than the non-existent model variable name.

Upvotes: 0

keeehlan
keeehlan

Reputation: 8054

After much frustrating troubleshooting, I decided to try something a little out-of-the-box... I restarted Visual Studio. After that, I was able to access my members like so:

@Html.RenderPartial("_Course", Model.CourseCompletion);

However, this presented a new problem. I received this error on the whole line:

Cannot implicitly convert type 'void' to 'object'

I realized that the statement was attempting to return a value, so I wrapped it in curly brackets, like so:

@{Html.RenderPartial("_Course", Model.CourseCompletion);}

Voila. Problem solved, data accessible, models working. I am flabbergasted.

Upvotes: 2

Related Questions