Is it possible to put html element in aspx if funtion? - asp.net

Could it possible to put element in if function in ASP.NET like in ASP.NET MVC Razor view?
Maybe something like this :
<% if (Visible)
{
<div>I want to determine here</div>
} %>
But this will show error... I knew it could solve by using javascript or div with codebehind:
<div style="<%=isNotGame? "display:none":"display:block" %>"></div>
or:
<div runat="server" id="codeBehind"></div>
CodeBehind.InnerHTML="...";
Q1: Is it possible? If yes, how?
Q2: Why I want to do this is because I think if I don't want to show an element, it is better not to create the element than create and hide it, is it correct?

Yes it is possible, try this instead.
<%
if (Visible)
{
%>
<div>I want to determine here</div>
<%
}
%>
The 2nd question, in my opinion if you don't need it then there is no reason to take up the resources. Keep in mind that this is all data transferring over the wire. Depending on how many wasted elements you create it can add up fast and depending on what you are doing it may have a number of adverse affects. Many people pay for data on mobile devices. Search engines could penalize you for performance losses due to high volumes of data you never cared to send anyway.

As your original question says about razor syntax, it can be done as -
#if (Visible) {
<div>I want to determine here</div>
}
If you want more information on razor syntax, Check this
Answer to your question 2 is tricky. You can render whatever elements you want and take decision at code behind but if you want to toggle some elements by specific conditions of your scenario then it is better to do it by Javascript as for toggling requesting server to do it for client is bad approach.

It is possible to generate HTML in your razor view, as per your condition
#if(condition){
<div>show this div</div>
}
And about Question2, do not render unnecessary . But in case you need that HTML to be made visible depending on user actions, then render the HTML, use CSS to hide the same. And then on client side you can make it visible.

Related

Facing Issue with Xmlwriter while writing nested items

I’m trying to use Xmlwriter to generate HTML output and came across this issue where HTML is not generating as expected.
My code look something like this.
writer.WriteStartElement("div");
writer.WriteAttributeString("class", "test");
writer.Flush();
//Load other control which write to same stream.
//other control generate o/p like this <div id=”other control”></div>
writer.WriteFullEndElement();
writer.Flush();
Output of this code is generating like this.
<div class="test"
<div id=”other control”></div>
></div>
But the expected output is
<div class="test">
<div id=”other control”></div>
</div>
Anyone faced same type of issue ?
Any suggestions ?
New to programing, so not sure about this
//writer.Flush(); //if you need a flush to come before your control
writer.WriteStartElement("div");
writer.WriteStartAttribute("class");
writer.WriteValue("test"); // OR writer.WriteString("test");
writer.WriteEndAttribute(); //perhaps this way is handled differently.
writer.WriteStartElement("control");// with no attributes to confuse it you might want to name it div
//then your other control stuff
writer.WriteEndElement();// end of the control element
writer.WriteEndElement();// end of the div.
writer.Flush();
I think the WriteEndElement decides whether it will be a /> or >< /elementname> or >UnknownStuff< / elementname>, so if it has something like your control or maybe the flush, that it does not know how to handle your control.
Since the last thing it was writing was an attribute, it regards your control as a odd looking attribute.
By placing your control in a element that could be called control or < div > the WriteEndElement might think it's a odd looking element.
Imagine how you might make the WriteEndElement if you were writing the XMLwriter class.
What is it going to deal with in it's life cycle.
How does it recognize that their are to be no more attributes because maybe you can trick it somehow.
If you find a way to get it working please put your answer up because I know I have been helped by reading years old forums and I have been noticing that usually the question is answer about six mouths latter which if your working on anything you probably thought of what to do by that time.

HTML tag to allow removable &nbsp

Does anyone know of a way to contain a nonbreaking space in an html tag to allow me to remove it based on conditions tested during runtime in the code behind?
Basically why I need this: if a condition is satisfied I will have 4 buttons, but if it's not only three. I can remove the button but then I have 4 in-between 2 of the buttons instead of just 2 .
Something like the <del> tag would work if it didn't strike through the text.
Basically I have something like this(propery values not included for simplicity):
<td><button />&nbsp&nbsp<button />&nbsp&nbsp<button />&nbsp&nbsp<button /></td>
I can't have the function in the actual button tag because then it will render the &nbsp instead of the button text.
EDIT:
I did end editing the &nbsp tags out and using css. I appreciate all of the responses.
The main reason that I was apprehensive to go that route to being with is because trying to get my client to approve anything is like pulling teeth, but I got them to approve the changes and adjust the budget.
Thanks again!!
Does it need to be ? Based on your description of the requirement, it sounds like a bit of CSS might work better:
button.myClass {
margin-left: 1ex;
}
Much simpler than trying to put logic in your view layer (even if you are not strictly following the MVC pattern you should still try to separate your presentation and business logic as much as possible).
You should not use for layout.
If you want to output some HTML content directly on the page without controls - you can use Embedded Code Blocks:
<button/><% =GetNecessaryNbsp() %><button/>
Where GetNecessaryNbsp() in the page class would return necessary number of .

Hide outer tables in ASP.NET

One of the features of a website I'm working on is that you can "maximize" the contents of the page, basically removing all the outer elements of the page, navigation, banners, etc.
This is currently done in what seems like the worst possible way:
<%
if (shouldBreakFrame)
{
%><!--#include file="header.include" --><%
}
%>
// Contents of page here
<%
if (shouldBreakFrame)
{
%><!--#include file="footer.include" --><%
}
%>
The footer is basically just closing tags from the header.
So I want to clean this up and am working on a master page, but I'm not sure how to properly "remove" the HTML elements that wrap the contents when we want to maximize the page. It would be easy for tags that open/close on one side or the other of the content, but what about div/tables that open at the top and close at the bottom?
Edit: To clarify exactly what the output looks like and why I can't just "hide" the elements with JavaScript code or the .Visible property here is what the output might look like and what it should look like after the surrounding elements are hidden:
<table>
<tr>
<td>Header</td>
</tr>
<tr>
<td>
Page content here
</td>
</tr>
</table>
And after hiding stuff all that is left is Page content here.
So if I just hide the table, the content would disappear as well.
You have a few options here, both require the elements to be already contained within the markup (unless you want to go down the ajax route).
The first would be using CSS to show/hide elements via the display:none attribute thats explained here. However I would have to say may favourite method would be to use jQuery. This contains two functions, show() and hide() but interestingly also includes a toggle() function which will show/hide elements depending on their current visibility. This should allow your code to be tidier and wouldn't have to worry about if(shouldBreakFrame). I found this interesting article on it which should get you started.
The only other option I can think of is either duplicate the code (in the same masterpage) or have two seperate masterpages. After all a masterpage is basically a template, and thats the part you want to change.

ID naming convention in ASP.NET?

Coming from the world of HTML, XML and PHP its a new way of thinking when making web applications using ASP.NET. I'd like to use the following code in my MasterPage:
<div id="leftnav">
<asp:ContentPlaceHolder ID="leftnav" runat="server">
</asp:ContentPlaceHolder>
</div>
But since leftnav in this example is used twice, Visual Studio make a small but noticable protest. How should I think in this situation, and which is the most appropriate use of naming ID's in ASP.NET.
I don't like the default naming since id="ContentPlaceHolder1" says nothing of the content.
Thank you for listening!
I would call the div "nav" and the placeholder "navPlaceholder". This is because the word "left" implies position, which should be handled soley by your css, not your html. What if the designers decided they wanted to put the navigation on the right? You could do this in your css, but you would end up with something confusing like div #lefnav { float:right; } a trivial example, I know but something to keep in mind.
How about "leftNavPlaceHolder"?
Just as along as your consistent with your naming convention :)
No, the default IDs are terrible. I can't imagine they're meant to be used, it's just that Visual Studio isn't intelligent enough to suggest anything better, and they're not suggesting something semi-intelligent, because they don't want to try to come off as something they're not. Reasonable =)
So make a habit of always changing the default IDs. What you change them to is completely up to you; "leftNavContent"? Pretty much the only thing that's coverned by convention is capitalization, when it comes to IDs.
The only thing that should really change from pure HTML is that you can't use IDs like "left-navigation", i.e. containing hyphens, for server controls.
I would suggest, don't give id to div unless you really need, because it will impact on performance.
Subjective. The obvious answer to this type of question is: Pick something that you like; standardise it, and always follow it.
Personally, I name my things in the following fashion:
<asp:Literal runat="server" ID="ltlDescriptionOfContent" />
or
<asp:PlaceHolder runat="server" ID="plhSendMessage">
</asp:PlaceHolder>
For an area that contains, yes, information about sending a message. But you don't have to do this. Do whatever you want. Just make it consistent. And ideally, convey a little information about what is within.
I prefix all ASP.Net controls with ux to mean user control.
Then you can hook up your String emailAddress = "test#abc.com"; to your uxEmailAddress.Text = emailAddress

How can I use a traditional HTML id attribute with an ASP.net runat='server' tag?

I am refactoring some CSS on a website. I have been working on, and noticed the absence of traditional HTML IDs in the code.
There is heavy use of CssClass='…', or sometimes just class='…', but I can't seem to find a way to say id='…' and not have it swapped out by the server.
Here is an example:
<span id='position_title' runat='server'>Manager</span>
When the response comes back from the server, I get:
<span id='$aspnet$crap$here$position_title'>Manager</span>
Any help here?
Use jQuery to select the element:
$("span[id$='position_title']")....
jQuery's flexible selectors, especially its 'begins with'/'ends with selectors' (the 'end with' selector is shown above, provide a great way around ASP.NET's dom id munge.
rp
The 'crap' placed in front of the id is related to the container(s) of the control and there is no way (as far as I know) to prevent this behavior, other than not putting it in any container.
If you need to refer to the id in script, you can use the ClientID of the control, like so:
<script type="text/javascript">
var theSpan = document.getElementById('<%= position_title.ClientID %>');
</script>
Most of the fixes suggested her are overkill for a very simple problem. Just have separate divs and spans that you target with CSS. Don't target the ASP.NET controls directly if you want to use IDs.
<span id="FooContainer">
<span runat="server" id="Foo" >
......
<span>
</span>
You can embed your CSS within the page, sprinkled with some server tags to overcome the problem. At runtime the code blocks will be replaced with the ASP.NET generated IDs.
For example:
[style type="text/css"]
#<%= AspNetId.ClientID %> {
... styles go here...
}
[/style]
[script type="text/javascript"]
document.getElementById("<%= AspNetId.ClientID %>");
[/script]
You could go a bit further and have some code files that generate CSS too, if you wanted to have your CSS contained within a separate file.
Also, I may be jumping the gun a bit here, but you could use the ASP.NET MVC stuff (not yet officially released as of this writing) which gets away from the Web Forms and gives you total control over the markup generated.
Ok, I guess the jury is out on this one.
#leddt, I already knew that the 'crap' was the containers surrounding it, but I thought maybe Microsoft would have left a backdoor to leave the ID alone. Regenerating CSS files on every use by including ClientIDs would be a horrible idea.
I'm either left with using classes everywhere, or some garbled looking IDs hardcoded in the css.
#Matt Dawdy: There are some great uses for IDs in CSS, primarily when you want to style an element that you know only appears once in either the website or a page, such as a logout button or masthead.
The best thing to do here is give it a unique class name.
You're likely going to have to remove the runat="server" from the span and then place a within the span so you can stylize the span and still have the dynamic internal content.
Not an elegant or easy solution (and it requires a recompile), but it works.
.Net will always replace your id values with some mangled (every so slightly predictable, but still don't count on it) value. Do you really NEED to have that id runat=server? If you don't put in runat=server, then it won't mangle it...
ADDED:
Like leddt said, you can reference the span (or any runat=server with an id) by using ClientID, but I don't think that works in CSS.
But I think that you have a larger problem if your CSS is using ID based selectors. You can't re-use an ID. You can't have multiple items on the same page with the same ID. .Net will complain about that.
So, with that in mind, is your job of refactoring the CSS getting to be a bit larger in scope?
I don't know of a way to stop .NET from mangling the ID, but I can think of a couple ways to work around it:
1 - Nest spans, one with runat="server", one without:
<style type="text/css">
#position_title { // Whatever
}
<span id="position_titleserver" runat="server"><span id="position_title">Manager</span></span>
2 - As Joel Coehoorn suggested, use a unique class name instead. Already using the class for something? Doesn't matter, you can use more than 1! This...
<style type="text/css">
.position_title { font-weight: bold; }
.foo { color: red; }
.bar { font-style: italic; }
</style>
<span id="thiswillbemangled" class="foo bar position_title" runat="server">Manager</span>
...will display this:
Manager
3 - Write a Javascript function to fix the IDs after the page loads
function fixIds()
{
var tagList = document.getElementsByTagName("*");
for(var i=0;i<tagList.length;i++)
{
if(tagList[i].id)
{
if(tagList[i].id.indexOf('$') > -1)
{
var tempArray = tagList[i].id.split("$");
tagList[i].id = tempArray[tempArray.length - 1];
}
}
}
}
If you're fearing classitus, try using an id on a parent or child selector that contains the element that you wish to style. This parent element should NOT have the runat server applied. Simply put, it's a good idea to plan your structural containers to not run code behind (ie. no runat), that way you can access major portions of your application/site using non-altered IDs. If it's too late to do so, add a wrapper div/span or use the class solution as mentioned.
Is there a particular reason that you want the controls to be runat="server"?
If so, I second the use of < asp : Literal > . . .
It should do the job for you as you will still be able to edit the data in code behind.
I usually make my own control that extends WebControl or HtmlGenericControl, and I override ClientID - returning the ID property instead of the generated ClientID. This will cause any transformation that .NET does to the ClientID because of naming containers to be reverted back to the original id that you specified in tag markup. This is great if you are using client side libraries like jQuery and need predictable unique ids, but tough if you rely on viewstate for anything server-side.
If you are accessing the span or whatever tag is giving you problems from the C# or VB code behind, then the runat="server" has to remain and you should use instead <span class="some_class" id="someID">. If you are not accessing the tag in the code behind, then remove the runat="server".

Resources