Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically inject a partial view (or code) based on the current page (MVC3/Razor)?

I'm not able to get a clear answer on my problem: I want to have one partial view but have 3 distinct code blocks within the partial with similar (not exactly the same) content. So that whatever view page is loaded will determine which of the 3 code blocks is displayed in the partial view.

I did something similar back in MVC2, but it was on the controller level (controller determined which of the 3 code blocks was displayed). Now I have a need to go deeper and do it on the page level.

I understand that a bunch of if/else statements in a view is not the MVC convention. But honestly, that's the only way I know how to do it. An alternative is to keep this if/else logic and create more than one controller and keep doing it the old way.

Can anyone point me in the right direction?

like image 426
REMESQ Avatar asked Dec 11 '25 22:12

REMESQ


1 Answers

There's at least 4 ways you could do this.

  1. If/Else, like @StanK mentions
  2. Invoke a child action from the main view. Build logic into the action to render a different partial based on said logic.
  3. Create a custom HTML helper which extends @Html.Partial by checking your custom logic before rendering a different partial (essentially moving the if/else to the HTML helper)
  4. Add some OO to your model. Create an abstract class, and a deriving class for each of the 3 "similar, but different" code blocks, and a matching editor template for each. Then in your main view, call @Html.EditorFor(model => model.SomethingDeclaredAbstract) and MVC will pick the right template.

Hard to advise on which one, given you haven't supplied much code and you haven't said what's different about the 3 pieces of content.

I usually go with option 4 because it's the cleanest and most versatile.

like image 105
RPM1984 Avatar answered Dec 16 '25 00:12

RPM1984



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!