I need to write some code that places one of 3 choices of "blocks" of html in a specified place on the page. How can I do this?
I was thinking I can use single value databinding, but I don't think this is the correct way.
I'm using ASP.NET c#.
Edit: here is what it might look like:
MapPlaceholder.InnerHtml = #"<div class="mapContainer smallMap" id="smallGrid" runat="server" visible="false">
<div id="node1" class="gridBox" runat="server">
</div>
<div id="node2" class="gridBox" runat="server">
</div>
<div id="node3" class="gridBox" runat="server">
</div>
<div id="node4" class="gridBox" runat="server">
</div>
<div id="node5" class="gridBox" runat="server">
</div>
<div id="node6" class="gridBox" runat="server">
</div>
<div id="node7" class="gridBox" runat="server">
</div>
<div id="node8" class="gridBox" runat="server">
</div>
<div id="node9" class="gridBox" runat="server">
</div>
</div>";
and in the .aspx page:
<div id="MapPlaceholder" runat="server"></div>
One more thing, how can I tell C# to actually write the " in the string? It isnt working currently because it stop at the first " it finds.
Edit: I have another problem.
MapPlaceholder.InnerHtml = block1;
HtmlGenericControl smallGrid = (HtmlGenericControl)MapPlaceholder.FindControl("smallGrid");
containerName = "smallGrid";
smallGrid.Visible = true;
smallGrid.Attributes["Style"] = "background-image:url('" + du.getMapBackgroundImage(mapId) + "'); " + "width:300px; height:300px;";
containerName = "smallGrid";
This is what i am trying to do, but the FindControl always returns null. I debugged this and it seems that the html code is being added, but only after the pageload ends. Is there anyway i can tell c# to "render" the div so i can work with it like i need to?
To have double quotes in code, you need to have two of them when using # so it would be:
MapPlaceholder.InnerHtml = #"<div class=""mapContainer smallMap"" id=""smallGrid"" runat=""server"" visible=""false"">
<div id=""node1"" class=""gridBox"" runat=""server"">
</div>
<div id=""node2"" class=""gridBox"" runat=""server"">
</div>
<div id=""node3"" class=""gridBox"" runat=""server"">
</div>
<div id=""node4"" class=""gridBox"" runat=""server"">
</div>
<div id=""node5"" class=""gridBox"" runat=""server"">
</div>
<div id=""node6"" class=""gridBox"" runat=""server"">
</div>
<div id=""node7"" class=""gridBox"" runat=""server"">
</div>
<div id=""node8"" class=""gridBox"" runat=""server"">
</div>
<div id=""node9"" class=""gridBox"" runat=""server"">
</div>
</div>";
To your original question: have three strings with the possible "blocks" then assign the proper string:
string block1 = #"<div class=""mapContainer smallMap"">block 1</div>......";
string block2 = #"<div class=""mapContainer smallMap"">block 2</div>......";
string block3 = #"<div class=""mapContainer smallMap"">block 3</div>.......";
switch (myCond) {
case 1:
MapPlaceholder.InnerHtml= block1;
break;
case 2:
MapPlaceholder.InnerHtml= block2;
break;
case 3:
MapPlaceholder.InnerHtml= block3;
break;
}
Edit: looks like you need different approach. First, put all blocks inside the .aspx under MapPlaceholder control directly:
<div id="MapPlaceholder" runat="server">
<div class="mapContainer smallMap" id="smallGrid1" runat="server" visible="false">
block 1 contents here...
</div>
<div class="mapContainer smallMap" id="smallGrid2" runat="server" visible="false">
block 2 contents here...
</div>
<div class="mapContainer smallMap" id="smallGrid3" runat="server" visible="false">
block 3 contents here...
</div>
</div>
Having this, just show the proper control based on the condition:
switch (myCond) {
case 1:
smallGrid1.Visible = true;
break;
case 2:
smallGrid2.Visible = true;
break;
case 3:
smallGrid3.Visible = true;
break;
}
This way you don't have to mess with strings of raw HTML and can change the layout from the .aspx which is more convenient.
on Page Load you can insert what you need dynamically.
a tip: you can insert with a Label over its Text property an html block, javascript or jquery codes
Label myLabel = new Label();
myLabel.Text = #"html text";
Page.Controls.Add(myLabel);
If the question really is "how to place blocks of HTML onto the page" as a (very basic) example, you might find something like this useful:
ASPX code:
<div runat="server" id="mydiv"></div>
C# code:
mydiv.InnerHtml = "<span>hi</span>";
or
HtmlGenericControl c = new HtmlGenericControl("span");
c.InnerHtml = "hi";
mydiv.Controls.Add(c);
DataBinding is more for pushing dynamic values to page content from, e.g. a database.
The PlaceHolder control may be what you need:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.placeholder.aspx
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
protected void Button1_Click(object sender, EventArgs e)
{
Label NewLabel = new Label();
NewLabel.Text = "Hello World!";
PlaceHolder1.Controls.Add(NewLabel);
}
You can add HTML tags With concatenation of the string at label text or others
labelc.text="Html tags code here";
Related
Would someone give a code example how to create and insert HTML at run time?
The HTML is like this:
<div class="row">
<div class="col-md-3">
<img src="example.png" class="profileImage" /> <br />
<span class="name">Name</span>
<div class="ver"></div>
<img class="flag ver" src="star.png" />
<div class="horizontalBar"></div>
</div>
</div>
The close I get was:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Header.DataBind();
ContentPlaceHolder contents = Page.Master.FindControl("MainContent") as ContentPlaceHolder;
Panel row = new Panel() { CssClass = "row" };
Panel col = new Panel() { CssClass = "col-md-3" };
Image profile = new Image()
{
CssClass = "profileImage",
ImageUrl = "example.jpg"
};
row.Controls.Add(col);
col.Controls.Add(profile);
contents.Controls.Add(row);
}
}
It doesn't work (see below error) and isn't full code, for example, what class is equivalent to generate <span>?
I get this error:
The Controls collection cannot be modified because the control
contains code blocks
What's the reason of that error? which are those code blocks and how do I fix this?
I've tested the code here and it's working.
The control equivalent to span is Label, but I think there must be better ways of doing this.
If you really need to dynamically insert HTML code, you can inject it using the LiteralControl, like this:
var html = new LiteralControl(#"<div class=""row"">
<div class=""col-md-3"">
<img src=""example.png"" class=""profileImage"" />
<br />
<span class=""name"">Name</span>
<div class=""ver""></div>
<img class=""flag ver"" src=""star.png"" />
<div class=""horizontalBar""></div>
</div>
</div>");
contents.Controls.Add(html);
well how the title says, how can I add various <li> tags to a <ul> tag from code behind. I tried this Add to List from codebehind C# Asp.net this is my example code.
ASP
<body>
<form id="form1" runat="server">
<div>
<ul id="menu" runat="server"> </ul>
</div>
</form>
And code behind.
protected void Page_Load(object sender, EventArgs e)
{
CreateMenu();
}
protected void CreateMenu()
{
HtmlGenericControl li = new HtmlGenericControl("li");
menu.Controls.Add(li);
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "login.aspx");
anchor.InnerText = "login";
li.Controls.Add(anchor);
}
Well it works perfectly but maybe this gonna be a dumb question, how can I add more than one element to the <ul> tag? I need to create an new object for each item (I think this is wrong) or exist a better way to do this?
I searched but any example satisfies my doubt, sorry if you think is a repeated question.
If your datas(menu items) are not coming from a source(something like database), you need to repeat the same process over and over again unfortunately. Or you can create a function which is taking 2 parameters, text and link. This way you can do this job with 1 line.
private void AddMenuItem(string text, string link)
{
HtmlGenericControl li = new HtmlGenericControl("li");
menu.Controls.Add(li);
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", link);
anchor.InnerText = text;
li.Controls.Add(anchor);
}
AddMenuItem("text","link");
AddMenuItem("text2","link2");
AddMenuItem("text3","link3");
You can improve this for your specific needs.
You can use ListView. It's easier format. I also found a good tutorial about it (http://weblogs.asp.net/scottgu/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui)
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<div>
<p class="name"><%# Eval("author") %></p>
<p class="date"><%# Eval("insertDate") %></p>
</div>
<p class="comment"><span class="<%# Eval("icon") %>"></span><%# HttpUtility.HtmlEncode(Eval("comment")) %></p>
</li>
</ItemTemplate>
</asp:ListView>
I have an asp.net webfore application which on the page i have an accordion and in that it has some fields. On the first asp:textbox it has an onclick as it checks my db to see if the user exists or not. If they do an asp:Label is then displayed.
The issue i have is that when ever i click outside or tab out this field my accordion closes and i need it to stay open. I was think though is is possible to do this via JQuery even though my field has the onclick or do i need to add it to my code behind?
In my view i tried
$("#MainContent_txtRemoveUser").on("blur", function ()
{
if ($('#MainContent_txtRemoveUser').val() != '')
{
$('panel-collapse collapse').removeClass('collapse');
$(this).addClass('in');
}
});
but it doesn't work
In my code behind i tried
#region Checks if user exists in 'Users' db when field clicked out of
protected void txtRemoveUser_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtRemoveUser.Text))
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT 1 FROM Users WHERE Name = #Name", conn);
cmd.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
removeUserNotExist.Visible = false;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>function endRequestHandler(sender, args){$('#collapseOne').collapse.in()};</script>", false);
}
else
{
removeUserNotExist.Visible = true;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>function endRequestHandler(sender, args){$('#collapseOne').collapse.in()};</script>", false);
}
}
}
#endregion
but this too doesn't work
The HTML of my accordion is
<div id="RemoveUser" class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="accordion-toggle collapsed">Remove Users From The List</a>
</h3>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<p>If you would like to remove yourself or someone else from the list, please populate all the fields below ensuring to enter the <b>FULL</b> name of the user (whether its you or another user) and then click the 'Remove From List' button.</p>
<asp:Label ID="removeUserNotExist" runat="server" Text="The user entered does not exist. Please try again." Visible="false" style="color: red"></asp:Label>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtRemoveUser" CssClass="col-sm-offset-2 col-sm-3 control-label">Enter Name To Be Removed</asp:Label>
<div class="col-sm-3">
<asp:TextBox runat="server" ID="txtRemoveUser" CssClass="form-control" AutoPostBack="true" OnTextChanged="txtRemoveUser_TextChanged" />
</div>
</div>
<div class="row">
<div class="col-sm-offset-8 col-sm-3" style="padding-left: 0px">
<asp:Button runat="server" ID="btnRemoveUser" Text="Remove From List" CssClass="btn btn-danger" data-toggle="modal" data-target="#removeUserModal" data-backdrop="static" data-keyboard="false" ToolTip="Click to remove the specified user from the payday lunch list." />
</div>
</div>
</div>
</div>
</div>
</div>
None of these appear to work. I may be completly wrong in what i have done though.
The state of the accordion is getting lost on postback (which gets triggered on the textbox's text change event). One way to handle this is to maintain the value in a hidden field and then use this value to reset the accordion.
In .aspx add
<asp:HiddenField runat="server" ID="SetAccVisible" />
Then the corresponding javascript changes to:
$('document').ready(function () {
var hdnFldId = '<%= SetAccVisible.ClientID %>';
$("#txtRemoveUser").on("blur", function () {
//Set value of hidden field to show panel after postback
$('#' + hdnFldId).val(true);
});
if ($('#' + hdnFldId).val() == 'true') {
showPanel();
//lets reset the value
$('#' + hdnFldId).val(false);
}
function showPanel() {
if ($('#MainContent_txtRemoveUser').val() != '') {
$('.panel-collapse').removeClass('collapse').addClass('in');
}
}
});
You are missing class selector to target element. It should be:
$('.panel-collapse.collapse').removeClass('collapse');
In your Jquery, you have a little problem with your selector :
$("#MainContent_txtRemoveUser").on("blur", function ()
{
if ($('#MainContent_txtRemoveUser').val() != '')
{
$('.panel-collapse .collapse').removeClass('collapse');
$(this).addClass('in');
}
});
You forget the point before the class selector ;)
You can read more about JQuery selector here =>
https://api.jquery.com/class-selector/
Also, you can optimize your Jquery code :
$("#MainContent_txtRemoveUser").on("blur", function ()
{
if ($(this).val()) // == if $(#MainContent_txtRemoveUser).val() != ""
{
$('.panel-collapse .collapse').removeClass('collapse');
$(this).addClass('in');
}
});
You check the value of the selector's function (#MainContent_txtRemoveUser")
You can use the '$(this)' selector for call it again, in the function. ^^
And, don't forgot you can use a breakpoint in your browser for check your javascript!
Hope I help you :p
I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the <h3> or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
}
I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(
Just add this script function in your code and in body write onload and call that function.
Javascript:
<script type="text/javascript">
function startProgram() {
setTimeout('errorcheck()', 2000);
}
function errorcheck() {
setTimeout('errorcheck()', 2000);
document.getElementById("NewsTitlePreview").innerText = document.getElementById("Titletxt").value
document.getElementById("NewsContentPreview").innerText = document.getElementById("Contenttxt").value
}
</script>
<body onload="startProgram();">
<form id="form1" runat="server">
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
</body>
You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:
The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.
So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.
Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
<asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.
<script>
$(document).ready(function () {
$('#Titletxt').on('input', function () {
$("#NewsTitlePreview").text($(this).val());
});
$("#Contenttxt").on('input',function () {
$("#NewsContentPreview").text($(this).val());
});
});
</script>
One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}
Try this it will work this how change event call using jquery dont forget to add google apis
<script>
$('#txtbox').change(function() {
alert("change Event");
});
</script>
I have a bootstrap alert like so :
<div class="alert alert-danger">
×
First Error
</div>
My problem is I want to be able to change this text dynamically in my code behind, c#. Ideally, I would like to have multiple bullet pointed error messages in one alert like the image below:
Can anyone provide me with any ideas of how to achieve this?
In your html, have this
<div id="BootstrapErrorMessage" runat="server">
</div>
and in your code, do this
....
MyErrorString += "<li>Bad Password</li>";
....
MyErrorString += "<li>Invalid Date</li>";
....
if (!MyErrorString.isNullOrEmpty()) {
BootstrapErrorMessage.InnerHtml += "×" +
"<ul>" + MyErrorString + "</ul>";
BootstrapErrorMessage.Attributes["class"] = "alert alert-danger";
}
You can download the error messages to the client when he request the model of your page(recommended solution). Or you can post your data to the server and get list of errors to show.
Your html code should be like this:
<div class="bs-example">
<div class="alert alert-danger fade in">
<ul>
<li><strong>First</strong> Error </li>
<li>Second Error</li>
</ul>
</div>
</div>
And each li element should be updated from server(One of the options you choose).