Rendering a button in C# code-behind - c#

I'm trying to build a table in code-behind. What I have looks like this:
Content += "<tr>";
Content += "<td>" + dt.Rows[i]["Provision"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["MarkForReview"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["IssueType"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["Resolution"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["Feedback"].ToString() + "</td>";
Content += "<td><input type=\"button\" ID=\"btnEdit\" runat=\"server\" OnClick=\"btnEdit_OnClick\" Text=\"Edit\" /></td>";
Content += "</tr>";
The problem is in how I'm rendering the Edit button. When the code runs, what's rendered for the button looks like this:
<td><input type="button" ID="btnEdit" runat="server" OnClick="btnEdit_OnClick" Text="Edit" /></td>
it keeps giving me a "JavaScript runtime error" that btnEdit_OnClick doesn't exist, but I have this in my code-behind:
protected void btnEdit_OnClick(object sender, EventArgs e)
{
MdlCommentsExtender.Enabled = true;
MdlCommentsExtender.Show();
ScriptManager.GetCurrent(this).SetFocus(this.txtCommentBox);
}
Also, the button renders with no text. It's just a small gray button.
Any ideas what I'm doing wrong?

You can render a button as a literal. However, no event will be attached to it, because it is not in the control tree.
In other words, the click event will not be trigger when the button posts back to server.
Here is an example -
protected void Page_Init(object sender, EventArgs e)
{
var btnEdit = new Button {ID = "btnEdit", Text = "Edit" };
btnEdit.Click += btnEdit_OnClick;
PlaceHolder1.Controls.Add(btnEdit);
}
ASPX
<%# Page Language="C#" ... %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
</form>
</body>

Related

Remove Span tag generated in asp.net text label

I cannot remove the span tag which auto generated with the image tag.
Asp.net Code :
if (!IsPostBack)
{
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
SiteManagementService siteMng = new SiteManagementService();
LogedUserDTO logedUser = siteMng.GetLogedUserByUserId(Session["UserLoginID"].ToString().Trim());
LabelUser.Text = logedUser.FullName + " | " + logedUser.Company.CompanyDesc;
**LabelImage.Text = "<img src=\"" + siteMng.GetUserImageUrl() + logedUser.ProfileImage + "\" class='img-avatar' />";**
LabelDatetime.Text = DateTime.Now.ToString();
Session["UserAccessLevel"] = logedUser.UserGroupId;
Session["UserCompanyId"] = logedUser.CompanyId;
RepeaterMenu.DataSource = siteMng.GetMenuByUserGroup(logedUser.UserGroupId);
RepeaterMenu.DataBind();
LabelMasterFooter.Text = "© 2013 " + ResourceData.CompanyName + ". All rights reserved.";
}
Front End Code :
<asp:Label ID="LabelImage" runat="server" ></asp:Label>
Generated HTML Code :
<span id="ContentPlaceHolderHeader_LabelImage"><img src="UploadedFiles/ProPicturs/Img_1711.JPG" class="img-avatar"></span>
Code i want is just
<img src="UploadedFiles/ProPicturs/Img_1711.JPG" class="img-avatar">
If you want to only use an image tag, there is an Image tag in asp.net
protected string image_tag; // add this var in your page class and set it as protected
...
if (!IsPostBack)
{
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
SiteManagementService siteMng = new SiteManagementService();
LogedUserDTO logedUser = siteMng.GetLogedUserByUserId(Session["UserLoginID"].ToString().Trim());
LabelUser.Text = logedUser.FullName + " | " + logedUser.Company.CompanyDesc;
image_tag = "<img src=\"" + siteMng.GetUserImageUrl() + logedUser.ProfileImage + "\" class='img-avatar' />";
LabelDatetime.Text = DateTime.Now.ToString();
Session["UserAccessLevel"] = logedUser.UserGroupId;
Session["UserCompanyId"] = logedUser.CompanyId;
RepeaterMenu.DataSource = siteMng.GetMenuByUserGroup(logedUser.UserGroupId);
RepeaterMenu.DataBind();
LabelMasterFooter.Text = "© 2013 " + ResourceData.CompanyName + ". All rights reserved.";
}
you can try to use in .aspx page.
<%= image_tag %>
instead of
<asp:Label ID="LabelImage" runat="server" ></asp:Label>
A Label Control will add a HTML element to the page. Either as a div or a span element. So this
<asp:Label ID="Label1" runat="server" CssClass="MyLabel">
Content...
</asp:Label>
Becomes this
<span id="Label1" class="MyLabel">
Content...
</span>
But a PlaceHolder does not generate it's own html element. So the following code
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Content...
</asp:PlaceHolder>
Will generate
Content...
But there are some downsides, as a PlaceHolder does not have a CssClass property.

asp button add through span not firing Click event

This is my front End Code in asp.net form
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<span id="Message" runat="server"></span>
<span id="myid" runat="server">
</span>
</asp:Content>
here is my code behind
protected void Page_Load(object sender, EventArgs e)
{
myid.InnerHtml = myid.InnerHtml + "<asp:Button ID=" + dbLayer.AddDoubleQuotes("Button_Update") + " name=" + dbLayer.AddDoubleQuotes("Button_Update") + " runat=" + dbLayer.AddDoubleQuotes("server") + " class=" + dbLayer.AddDoubleQuotes("btn btn-success") + " OnClick=" + dbLayer.AddDoubleQuotes("Button_Update_Click") + " Text=" + dbLayer.AddDoubleQuotes("UpdateButton") + " />";
}
protected void Button_Update_Click(Object sender, EventArgs e)
{
Message.InnerHtml = "This Event Fired Sucessfully ...";
}
i am using web Method for Double Quotes
[WebMethod]
public string AddDoubleQuotes(string value)
{
return "\"" + value + "\"";
}
Not Able to get button click event
your reply helps me lot, i am stuck due to this
First of all, you cannot just simply render Server Control as string literal in ASP.Net Web Form.
Dynamically added server controls are a little bit tricky since they are not in control tree. You need to reload them back with same ID inside either Page_Init or Page_Load event.
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
<asp:Label runat="server" ID="MessageLabel" />
protected void Page_Init(object sender, EventArgs e)
{
var button = new Button {ID = "Button1"};
button.Click += Button_Click;
PlaceHolder1.Controls.Add(button);
}
private void Button_Click(object sender, EventArgs e)
{
MessageLabel.Text = "Button is clicked!";
}
FYI: Use ASP.Net Server control as much as possible instead of regular html control with runat="server", unless you absolutely certain that you do not need ViewState and some extra features offered by those server controls.
If EnableViewState is false, you can repopulate placeholder controls with different controls dynamically on a postback. The ids do not matter then.

Code added to CodeBehind not executing

I'm very new to Umbraco, I am still picking my way through how it works so it is entirely possible that I have missed something extremely obvious.
I have been asked to amend how a slider on a MasterPage functions, I've found the markup for the slider is in the .cs file for the MasterPage.
void CreateSlider()
{
if (!String.IsNullOrEmpty(CurrentContent.Slider1Image))
{
slider.InnerHtml += "<li class='foobar'>";
if (!String.IsNullOrEmpty(CurrentContent.Slider1Title))
{
slider.InnerHtml += "<img src='" + GetMedia(CurrentContent.Slider1Image) + "' alt='' />";
slider.InnerHtml += "<div class='slider_content bx-pager-item'>";
slider.InnerHtml += "<h1>" + CurrentContent.Slider1Title + "</h1>";
if (!String.IsNullOrEmpty(CurrentContent.Slider1VideoButtonTitle) && !String.IsNullOrEmpty(CurrentContent.Slider1VideoLink))
slider.InnerHtml += "<span>" + CurrentContent.Slider1VideoButtonTitle + "</span>";
slider.InnerHtml += "</div>";
if (!String.IsNullOrEmpty(CurrentContent.Slider1VideoButtonTitle) && !String.IsNullOrEmpty(CurrentContent.Slider1VideoLink))
{
slider.InnerHtml += "<div class='video_wrapper'>";
slider.InnerHtml += "<div class='youtube_container'>";
slider.InnerHtml += "<div><iframe src='https://player.vimeo.com/video/" + CurrentContent.Slider1VideoLink + "' width='100%' height='542' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>";
slider.InnerHtml += "</div>";
slider.InnerHtml += "</div>";
}
}
slider.InnerHtml += "</li>";
}
}
I have tried adding a class to the <li> but it doesn't not show up in the HTML markup at all. I have tried building the project but with no joy.
Here is the markup that is output:
<%# Master Language="C#" MasterPageFile="~/masterpages/Base.master" AutoEventWireup="true" Inherits="HomePageType1" Codebehind="HomePageType1.master.cs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<div class="slider_container">
<ul id="ContentPlaceHolderDefault_ContentPlaceHolder1_slider" class="bxslider">
<li>
<img src='/media/img001.jpg' alt='' />
<div class='slider_content'>
<!-- SLIDE CONTENT -->
</div>
<div class='video_wrapper'>
<div class='youtube_container'>
<div>
<!-- VIDEO URL -->
</div>
</div>
</div>
</li>
</ul>
</div>
</asp:Content>
Any suggestions?
Any code added to a .cs file outside of /App_Code/ must be compiled before it "counts" - that part should be dealt with when you build the project.
Also, the master page must reference its code behind for it to pick it up, like
<%# Master Language="C#"
AutoEventWireup="true" CodeBehind="MyMasterpage.master.cs" Inherits="MyNamespace.MyMasterpage" %>
Can you perhaps also share the master page content?
The reason this was not functioning correctly is because the previous developers had compiled their code but had also uploaded the C# files to the server. So the files we received were compiled.
After much political wrangling we got them to send us the uncompiled files which allowed me to make the code changes as expected.

How to add runat=server attribute to html buttons

I have multiple html buttons that generated from server side with a method on a csharp class.
the result is:
<button ID='btn1' runat='server' onserverclick='btn_Click'>Apply</button>
<button ID='btn2' runat='server' onserverclick='btn_Click'>Apply</button>
<button ID='btn3' runat='server' onserverclick='btn_Click'>Apply</button>
...
<button ID='btnN' runat='server' onserverclick='btn_Click'>Apply</button>
I also add btn_Click event to behind code:
protected void btn_Click (object sender, EventArgs e)
{
string id = (sender as Control).ClientID;
msg = id;
}
as you can see I want to get buttonId but when I click on any of buttons, btn_Click won't call and I can't get buttonId.
I am using asp.net website with c#4.0.
The problem is I need generate buttons using server side and runat attribute doesn't work with my method . how can I fix this problem?
this is my method body for generated buttons
for (int i = 0; i < dt.Rows.Count; i++)
{
DateTime dtTemp = DateTime.Parse(dt.Rows[i]["messageDate"].ToString());
if (dt.Rows[i]["isRead"].ToString() == "True")
readed = "MessageReaded";
else
readed = "MessageNew";
post += "<div class='modal fade' id='myModal" + dt.Rows[i]["messageId"].ToString() + "' tabindex='-1' role='dialog' aria-labelledby='myModalLabel'>"
+ "<div class='modal-dialog' role='document'>"
+ "<div class='modal-content'>"
+ "<div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button><h4 class='modal-title' id='myModalLabel'><span style='font-weight:bold'>subject</span> : " + dt.Rows[i]["subject"].ToString() + "</h4></div>"
+ "<div class='modal-header'><p><span style='font-weight:bold'>date</span> : " + dtTemp.ToString("yyyy/MM/dd") + "</p>"
+ "<p><span style='font-weight:bold'>Time</span> : " + dt.Rows[i]["messageTime"].ToString() + "</p>"
+ "<p><span style='font-weight:bold'>email</span> : " + dt.Rows[i]["email"].ToString() + "</p></div>"
+ "<div class='modal-body'>" + dt.Rows[i]["message"].ToString() + "</div>"
+ "<div class='modal-footer'><button type='button' class='btn btn-default' data-dismiss='modal'>close</button>"
+ "<button ID='btn" + dt.Rows[i]["messageId"].ToString() + "' class='btn btn-danger' onclick='DeleteMessage_Click'>Delete</button></div>"
+ "</div></div></div>";
string narrow = Special.TimeToNarrow(dt.Rows[i]["messageDate"].ToString(), dt.Rows[i]["messageTime"].ToString());
post += "<a data-toggle='modal' data-target='#myModal" + dt.Rows[i]["messageId"].ToString() + "' href='#' class='list-group-item " + readed + "'><span class='badge'>" + narrow + "</span><i class='fa fa-fw fa-comment'></i> <span>"
+ dt.Rows[i]["name"].ToString() + "</span> : <span>" + dt.Rows[i]["subject"].ToString() + "</span></a>";
}
So the problem is on
<button ID='btn" + dt.Rows[i]["messageId"].ToString() + "' runat='server' class='btn btn-danger' onserverclick='DeleteMessage_Click'>Delete</button>
EDIT MY POST : As you can see I can't use asp:button because using bootstrap modal. If you think that I can still use asp:button please write your code and show me how .thanks
As other's have said, the problem is ASP.NET won't recognise runat="server" when you generate your controls as a string of HTML.
Your code should probably be done in a much different way, but if you wanted a change to what you have already done that will work you could do this a little differently.
Instead of runat="server" on your buttons, make them submit buttons and assign them a name and value, for example...
Instead of this:
<button ID='btn1' runat='server' onserverclick='btn_Click'>Apply</button>
<button ID='btn2' runat='server' onserverclick='btn_Click'>Apply</button>
<button ID='btn3' runat='server' onserverclick='btn_Click'>Apply</button>
Do this (note they all have the same name):
<button name="btn" type="submit" value="1">Apply</button>
<button name="btn" type="submit" value="2">Apply</button>
<button name="btn" type="submit" value="3">Apply</button>
Then in your Page_Load event you can detect if one of these buttons was clicked with the following:
if (Page.IsPostBack)
{
if (Request.Form["btn"] != null)
{
//A btn was clicked, get it's value
int btn = int.Parse(Request.Form["btn"]);
//Do something with this btn number
}
}
Here's a little sample that has three buttons and displays the number of the button that was clicked:
Test.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button name="btn" type="submit" value="1">Apply</button>
<button name="btn" type="submit" value="2">Apply</button>
<button name="btn" type="submit" value="3">Apply</button>
</form>
</body>
</html>
test.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (Request.Form["btn"] != null)
{
int btn = int.Parse(Request.Form["btn"]);
Response.Write(btn);
}
}
}
}
There's no onserverclick in asp.
You should add the asp:Button tag instead of just Button and instead of onserverclick just OnClick
Something like:
<asp:Button ID='btn1' runat='server' Text="Apply" OnClick='btn_Click'/>
EDIT
The button generation method should look like this:
for (int i = 0; i < dt.Rows.Count; i++){
<div class='modal fade' id='myModal" + dt.Rows[i]["Id"].ToString() + "' tabindex='-1' role='dialog' aria-labelledby='myModalLabel'>
<div class='modal-dialog' role='document'>
<div class='modal-content'>
<div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button><h4 class='modal-title' id='myModalLabel'><span style='font-weight:bold'>subject</span> :subject</h4></div>
<div class='modal-header'><p><span style='font-weight:bold'>Date</span> : yyyy/MM/dd</p>
<p><span style='font-weight:bold'>Time</span>messageTime</p>
<p><span style='font-weight:bold'>Email</span>email</p>
</div>
<div class='modal-body'>message</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>close</button>
<asp:Button ID='btn" + dt.Rows[i]["messageId"].ToString() + "' runat='server' class='btn btn-danger' OnClick='DeleteMessage_Click'>Delete</button>
</div>
</div>
</div>
You can see that on this line: <button ID='btn" + dt.Rows[i]["messageId"].ToString() + "' runat='server' class='btn btn-danger' onserverclick='DeleteMessage_Click'>Delete</button> i have changed the button with asp:Button and the onserverclick with OnClick.
The previous comments are correct, there is no onserverclick in asp.net server control. onserverclick is available for html controls only.
Below code piece does the job;
protected void btn1_ServerClick(object sender, EventArgs e)
{
HtmlButton btn = (HtmlButton)sender;
btn.InnerText = btn.ID;
}
Cast the sender to HtmlButton to access the ID. You have to use the namespace 'System.Web.UI.HtmlControls'.
EDIT:
If the buttons are being dynamically generated then better to use server button control;
<asp:Button ID="btnAddUser" runat="server" Text="Add" OnClick="btnAddUser_Click" />

tooltip computed links for asp button after button is clicked

<ItemTemplate>
<tr>
<asp:LinkButton ID="btnID" runat="server"
ToolTip='The calculated IDs are: ' OnCommand="showIds"
CommandArgument='<%# Convert.ToInt32(Eval("Year")) + "," +
Convert.ToInt32(Eval("Month")) %>'>
<%# Convert.ToInt32(Eval("Count")) - Convert.ToInt32(Eval("LittleCount"))%>
</asp:LinkButton>
</tr>
</ItemTemplate>
As you can notice the tooltip text is static. In code behind, I do calculate and get some integers ( IDs ) every time the above button is clicked ( protected void showIds(object sender, CommandEventArgs e) { .... }) contained as a List<ExpressionListDictionary>. ( the asp:LinkButton is contained inside an asp:ListView )
What I want to do, is to change the tooltip into a dynamic one, containing all the already obtained IDs as links. ( Something like this: http://jsfiddle.net/IrvinDominin/jLkcs/5/ - but in my case I do need firstly to click the button for calculating the IDs, and after this I would need to change the tooltip text from code as it needs to show the respective IDs, as links if it is possible)
How can I achieve this?
If you have a class (or id or something) to identify the buttons you can make an jQuery document ready function to change the tooltip with ids to a link containing the ids.
I modifyed your fiddle: http://jsfiddle.net/jLkcs/545/
$(document).ready(function () {
$(".myLinkButton").each(function() {
createlink(this);
});
});
function createlink(obj){
var ids= $(obj).attr('title');
var linkHtml="<a href='javascript:alert(" + ids + ")'>link</a>"
$(obj).attr('title',linkHtml);
}
Why not simply adjust the ToolTip in the codebehind during postback?
protected void showIds(object sender, CommandEventArgs e)
{
((LinkButton)sender).ToolTip = "blahblah";
}
You can set your sender attributes if the CommandEventArgs CommandName is equal with your defined one
public void LinkButton_Command(Object sender, CommandEventArgs e)
{
if (e.CommandName.Equals("showIds"))
{
//
}
}
Here is an working example, this will work, not counting in what user control LinkButton is used:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
public string btnNoTooltip = "No IDs are calculated";
public string btnTooltip = "The calculated IDs are:";
protected void Page_Load(object sender, EventArgs e)
{
}
public void LinkButton_Command(Object sender, CommandEventArgs e)
{
if (e.CommandName.Equals("LinkButtonOrder"))
{
LinkButton lkTrigger = (LinkButton)sender;
if (lkTrigger.ToolTip.Equals(btnNoTooltip))
{
lkTrigger.ToolTip = btnTooltip + " " + e.CommandArgument;
}
else
{
lkTrigger.ToolTip += " " + e.CommandArgument;
}
Random random = new Random();
lkTrigger.CommandArgument = random.Next(0, 100).ToString();
Label1.Text = "Triggered: " + e.CommandName + " with Argument " + e.CommandArgument;
}
}
}
Markup:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h3>LinkButton Command Event Example</h3>
<asp:LinkButton id="LinkButton1"
Text="Order Item Here"
CommandName="LinkButtonOrder"
ToolTip='No IDs are calculated'
CommandArgument="01"
OnCommand="LinkButton_Command"
runat="server"/>
<br />
<asp:LinkButton id="LinkButton2"
Text="Or Order Item Here"
CommandName="LinkButtonOrder"
CommandArgument="02"
ToolTip='No IDs are calculated'
OnCommand="LinkButton_Command"
Runat="server"/>
<br />
<br />
<asp:Label id="Label1" runat="server"/>
<asp:PlaceHolder id="plhInjectId" runat="server" Visible="false"></asp:PlaceHolder>
</asp:Content>
You can use jquery to generate Tool Tip on Page itself.
Add a hidden field for your all the already obtained IDs (comma sepearted) to asp:ListView
Populate this hidden in ItemCreated event on server
add a class to your link button, say 'ShowHyperlinkOnHover'
Bind mouseenter event to class ShowHyperlinkOnHover document.ready function of jquery, this will dynamically generate tool tip. and then on Mouse Over tool tip will be displayed.
$(document).ready(function () {
$(document).on("mouseenter", ".ShowHyperlinkOnHover", function(this){
// 2 is index of hidden field having comma seperated Ids
var dynaToolTip;
$(this).parent("td:nth-child(2)").split(',').each(
function(oneId) dynaToolTip=dynaToolTip+ anyFomationLogic(oneId);
);
$(this).attr('title',dynaToolTip);
});
});

Categories