简体   繁体   中英

ASP.NET Dynamically change markup

Here's the scenario, I want a single page to display different content depending on a session variable. The issue is , the only solution I can think of for using a code-behind method is to hide the div showing the content but I just can't help but feel that it isn't secure. The other method I have in mind is to have code within the markup as you would do in PHP, for eg

<% if (Session["variable"].ToString() == "food") { %>
   //Markup
<% } %>

So do you think hiding a div doesn't have security risks or is there a better method for dynamically changing the content using code-behind?

The security concerns heavily depends on how Session["variable"] is set.

But a control set to runat="server" and Visible=false; is not even rendered to the client, so I don't see a problem with this approach.

In asp.net there are various controls which you can use to display different content depending on different variables.

For your solution you could use the <asp:PlaceHolder /> control. This would allow you to insert HTML markup and other controls into it, then in the code behind you can show/hide depending on your varialble.

So your markup on the .aspx page would be;

<asp:PlaceHolder runat="server" id="phOne" visible="false">
    <p>Show Me if condition is met</p>
</asp:PlaceHolder>

Then in your code behind you can show/hide;

this.phOne.visible = Session["variable"].ToString() == "food";

I would make sure that by default it is not visible visible="false" then show in the code. If the control is not visible, then is it not rendered on the page at all, so no security risk in this.

Another would be the <asp:Panel /> which renders as a <div /> on the page. This would work in the same fashion as the placeholder

Perhaps you want to use Server.Transfer . See more about it here: Server.Transfer Vs. Response.Redirect .

Of course, you can also simply set the content from codebehind:

<p id="a" runat="server">
    abc
</p>

And:

a.InnerHtml = "def";

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