Search code examples
c#asp.net-mvcasp.net-mvc-3partial-viewsstrong-typing

pass enum to strong typed partial view


I have an strong typed partial view that receives an enum:

@model MyEnum 
@{
   Layout = null
}
@if (Model == MyEnum.Value1) {
    //... dosomething
}
@if (Model == MyEnum.Value2) {
    //... do another thing
}

I can't call render partial properly like this

@{ Html.RenderPartial("MyPartialView", MyEnum.Value2); }

Any ideas?


Solution

  • Other than the fact that you are missing a ; after the null layout assignment I cannot see what prevents you from doing so (unable to repro as I like saying):

    @{
        Layout = null;
    }
    

    Here's a full working example illustrating that this should work.

    Model:

    public enum MyEnum
    {
        Value1,
        Value2
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
    

    Index.cshtml view:

    <div>
    @{ Html.RenderPartial("MyPartialView", MyEnum.Value2); }
    </div>
    

    MyPartialView.cshtml partial:

    @model MyEnum
    @{
        Layout = null;
    }
    @if (Model == MyEnum.Value1) {
        <div>Value 1 was selected</div>
    }
    @if (Model == MyEnum.Value2)
    {
        <div>Value 2 was selected</div>
    }
    

    which as expected outputs in the resulting HTML:

    <div>Value 2 was selected</div>