I have a main View which has several sections and a main dropdown at the top which defines how the rest of the view looks like. All these sections have some data that is visible all the time, and some that need to be hidden when certain values are chosen in the main dropdown.

As of now, I have partial views for each section, and I am having lots of if/else statements in my view to show/hide the specifics, which is getting clumsier by the day.

  • I assume the implied question here is "Is there a better way to do this"?
    – ozz
    Jul 21, 2014 at 12:27

1 Answer 1


My personal favorite would be to use knockout to accomplish this kind of page manipulation through a two-way binding with some kind of "security" class. I use quotes here because it really isn't security so much as it's just interface manipulation. Security should always be handled server side. However, with a good knockout model you would be able to use nomenclature as simple as data-bind="visible: displayModel.IsSpecialRole", and simply by updating the model you'd be able to have full control of each element. It's very simple to manage, and it is very simple to apply AJAX to make it even more dynamic.

Failing the usage of that, another technique that might be simpler to deploy would be a common display class that you insert into the ViewBag. I'm not a proponent of the ViewBag, I find it clumsy, but it would certainly be useful here. You could create a method or series of methods whose job would be to output the html attributes collection based on your conditionals. One of the outputs could be a css class that specifies only display: none to make sure it is not displayed on the page even if it is produced. This would still deliver html to the client side, but it would not be visible or usable to the client.

A third alternative available to you would be to create your own HtmlHelper extension method that accepts the arguments you need to base your conditional decisions on. It's return would be the rendered output of any actionlinks or raw html that would be produced. You have to be careful, though, to make sure that the extension doesn't generate anything that would be part of the template. It should only generate simple elements with css class attributes and default element attributes (src, href, etc.). The only real benefit to doing this would be that your conditionals would be abstracted into the extension method and your element definitions in your template would look simpler. A drawback is that your conditionals would be abstracted into the extension method. This may obfuscate the behavior for future developers/maintainers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.