I’m new to MVC 3 / Razor and working on a simple site to learn the basics. To that end, I’ve created a simple view that renders a DropDownList on a page at /Home/SignedInAs.
The logic in my Home Controller is:
public class HomeController : Controller
{
public ActionResult SignedInAs()
{
SignedInAsViewModel siavm = new SignedInAsViewModel();
siavm.SignedInAsOptions = db.GetSignedInAsOptions();
return View(siavm);
}
}
where SignedInAsViewModel is a simple:
public class SignedInAsViewModel
{
public SignedInAsViewModel()
{
this.SignedInAsOptions = new List<SignedInAs>();
}
public IEnumerable<SignedInAs> SignedInAsOptions { get; set; }
}
and the method, db.GetSignedInAsOptions() returns a List of SignedInAs objects with the properties, ID and Name.
And in Views/Home/SignedInAs.cshtml, I have:
@model myMVCApp.Views.SignedInAsViewModel
...
@Html.DropDownList("ddlSignedInAs", new SelectList(Model.SignedInAsOptions, "ID", "Name", selectedValue))
...
And the Select list renders exactly as expected on my page at /Home/SignedInAs.
What I really want to do is render the DropDownList at the top of every page. So, I created a partial view, _SignedInAsPartial:
@model myMVCApp.Views.SignedInAsViewModel
@if (Request.IsAuthenticated)
{
<text><div>@Html.DropDownList("ddlSignedInAs", new SelectList(Model.SignedInAsOptions, "ID", "Name", selectedValue))</div></text>
}
And a controller, SignedInAsController:
public class SignedInAsController : Controller
{
public ActionResult ShowSignedInAs()
{
SignedInAsViewModel siavm = new SignedInAsViewModel();
siavm.SignedInAsOptions = GetSignedInAsOptions();
return PartialView(siavm);
}
}
(I have tried return View(siavm) here as well.)
And in my _Layout.cshtml used by all pages I have:
@Html.Partial("_SignedInAsPartial")
Trying to load any page now results in a NullReferenceException and the visual debugger stops at _SignedInAsPartial.cshtml
Breakpoints never get hit in the SignedInAsController.
I obviously don’t understand something here, and I’ve read everything I can find. But I can’t figure it out. Why does the select list render fine on a page view, but not on a partial view?
You have to either pass the model to the partial view or you can use Html.RenderAction, which would require a controller action to back that view.