Can Html.Partial() accept a ViewBag to determine the partial view to render?

So I'm using Html.Partial() to render a partial view. This is a very basic MVC app to help me understand partial views and MVC as a whole.

I have a form that has a dropdown which changes what is displayed below said dropdown. If 'One' is selected, 'One' will be displayed, same with 'Two'. This is using a ViewBag which is changed within my controller. However, I want this to be displayed via a partial view. So I've got this @Html.Partial(ViewBag.Test). This doesn't work at all, it gives the CS1973 error.

Here's the full error I'm getting:

Error CS1973 'HtmlHelper' has no applicable method named 'Partial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched.

1 answer

  • answered 2019-03-20 14:59 Mahogany

    I managed to fix this by casting the contents of Html.Partial() to a string:Html.Partial((string)ViewBag.Test). I then put this inside an if statement to check if ViewBag.Test is null, because an error occured when ran as ViewBag.Test was not assigned to.

    This is what I ended up with that worked:

    @if (ViewBag.Test != null)
    {
        @Html.Partial((string)ViewBag.Test)
    }