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" />
Related
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.
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.
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>
I want to add some controls to my form dynamically.
in html side:
<asp:Literal ID="Literal_news" runat="server"></asp:Literal>
my code in c# (code behind) is like below:
string str_contxt = "hi dear user!";
img2.ImageUrl = "~/images/a.jpg";
Literal_news.Text += "<article style=\"position: relative; height: 300px; opacity: 1;\"> <div class=\"banner-wrap\"> <div class=\"slider-left\"> <img src =\" " + img2.ImageUrl + " \" alt=\"\"/> </div> <div class=\"slider-left\"> <asp:Label ID=\"Label1\" runat=\"server\" Text=\" " + str_contxt + " \"></asp:Label> </div> <div class=\"clear\"></div></div></article> ";
the image is shown correct (img2.ImageUrl), but the text isn't shown(str_contxt). what is the problem ?
{I used label instead of literal control. but the problem didn't solve.}
I have a question about server side and html side controls.
This is my code
ClientScript.RegisterStartupScript(this.GetType(),
"Enter Id",
" prompt('Enter your Id ....');",
true);
I want to get value that user entered?
What should I do?
Try this way
<form id="theform" runat="server">
<input type="hidden" id="hidValue" runat="server" />
</form>
Script for get value from hidden field
<script type="text/javascript">
function storeinput(id) {
document.getElementById("<%=hidValue.ClientID%>").value = id;
}
</script>
ClientScript.RegisterStartupScript(this.GetType(), "prompt", "var id = prompt('Enter your Id .'); storeinput(id);", true);
Please try below:
Please define hidden variable in ASPX page:
<input type="hidden" id="hidValue" runat="server" />
Please write below code at CodeBehind:
ClientScript.RegisterStartupScript(this.GetType(), "prompt", "document.getElementById('" + hidValue.ClientID + "').value = prompt('Enter your Id .'); alert(document.getElementById('" + hidValue.ClientID + "').value); ", true);