简体   繁体   中英

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM