Basically i tried to do what is recommended but somehow it doesn't work. the problem is i cannot take value of selected item in dropdown to textbox value. what i observed is JS code isn't triggered. What could be the problem?
my codes are;
HTML
<div class="dropdown show col-md-2 p-1">
<a class="btn btn-secondary btn-sm dropdown-toggle p-1" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" runat="server">Load Evaluation
</a>
<div id="dropdown" runat="server" class="dropdown-menu" aria-labelledby="dropdownMenuLink">
</div>
</div>
<div>
<asp:TextBox ID="dropLabel" runat="server" AutoPostBack="true" OnTextChanged="dropLabel_OnTextChanged" Style ="display:block"></asp:TextBox>
</div>
JS
$('#dropdown a').on('click', function () {
$('#dropLabel').val(this.text());
sessionStorage.setItem('label1', $(this).text());
location.reload(true);
})
C#
protected void dropLabel_OnTextChanged(object sender, EventArgs e)
{
var labelText = (sender as TextBox).Text;
//... do something with the text.
A3toSqlDataContext ctx4 = new A3toSqlDataContext();
var yukle = from c in ctx4.A3_Coaching
where c.name == labelText
select c;
C# for a tag including
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
A3toSqlDataContext ctx = new A3toSqlDataContext();
var alp = from c in ctx.A3_Coaching
select c.name;
foreach (var item in alp)
{
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "#");
anchor.InnerHtml = Convert.ToString(item);
anchor.Attributes.Add("class", "dropdown-item");
dropdown.Controls.Add(anchor);
}
}
}
The problem is, that your dropLabel might be a server-side control, but the actual javascript is happening on the client, so your asp.net application will not be aware of this until you do a postback to the server.
You should be able to do this, if you convert your droplabel to an invisible Textbox, that will do a Postback for you, when its text changes:
<div>
<asp:Textbox id="dropLabel" runat="server"
AutoPostback="true"
OnTextChanged="dropLabel_OnTextChanged"
style="display:none">
</asp:Textbox>
</div>
CodeBehind:
protected void dropLabel_TextChanged(object sender, EventArgs e)
{
var labelText = (sender as TextBox).Text
//... do something with the text.
}
Make sure you check for a PostBack in your Page_Load to not re-load everything and possibly overwrite your state using if(!IsPostBack) { /*... do regular Page_Load*/}
Related
I have a repeater using for getting an image nad a radio button on the bottom. I want to achieve a combination of this radio button (repeater speaking) with the property of autoexcluyent feature. How can I achieve it?
As far as I got ...
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
With this code I am getting a one radio button per each image but no one autoexcuyent even I am using GroupName property
USING NET FRAMEWORK 4.6.2.
I don't know if easy way to manage this situation however you can manage by below code. It will be good to wrap your contents into update panel so you can prevent page refresh on checkbox changed.
Additionally, IsChecked property being used to initialize checked on page load. You can remove if not required.
.ASPX
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<span>
<asp:RadioButton runat="server" ID="rb1" Checked='<%# Eval("IsChecked") %>' AutoPostBack="true" OnCheckedChanged="rb1_CheckedChanged" Text='<%#Eval("description").ToString()%>' />
</span>
</div>
</ItemTemplate>
</asp:Repeater>
.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<test1> lst = new List<test1>();
lst.Add(new test1() { Id = 1, description = "R1", IsChecked = false });
lst.Add(new test1() { Id = 3, description = "R2", IsChecked = true });
lst.Add(new test1() { Id = 2, description = "R3", IsChecked = false });
lst.Add(new test1() { Id = 4, description = "R4", IsChecked = false });
repeater1.DataSource = lst;
repeater1.DataBind();
}
}
protected void rb1_CheckedChanged(object sender, EventArgs e)
{
foreach (RepeaterItem item in repeater1.Items)
{
(item.FindControl("rb1") as RadioButton).Checked = false;
}
(sender as RadioButton).Checked = true;
}
After researching between SOF and a few forums I implemented a quite right solution using JS. I am handling another problem related with OnCheckedChanged´s event on RadioButton...
But the initial issue is fixed.
Forum Solution
I am posting the solution that works for me, using as base as a help coming from a forum, hoping it helps others as well with this bug.
REPEATER.
<asp:Repeater runat="server" ID="repeater1" OnItemDataBound="repeater1_ItemDataBound">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup" OnCheckedChanged="rb1_CheckedChanged"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
BACKEND
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rb1");
string script = "SetUniqueRadioButton('repeater1.*nameGroup',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
I am new working with webforms. I learned MVC first. I have a Telerik RadGrid that has a MasterTableView inside and then, a couple of columns inside this MasterTableView. I want to simply disable some buttons in the code behind but Visual Studio keeps telling me that the buttons does not exists. In a Google search I found that the reason is because the buttons are inside the RadGrid. However I didn't find any example to access them.
The buttons are inside the radgrid and they looks like this:
<telerik:GridTemplateColumn HeaderStyle-Width="72px" HeaderText="Acciones" >
<ItemTemplate >
<div style="width: 100px">
<span style="position:relative;" class="grid-buttonColor1">
<i class="material-icons">create</i>
<asp:Button ID="btnEditReportDetail"
CommandArgument='<%# Item.ReportDetailId %>'
OnClick="btnReportDetail_Click"
runat="server"
Style="position:absolute; opacity:0; top:0; left:0; width:100%; height:100%;"
type="button"
causesvalidation="false" />
</span>
<span style="position: relative;" class="grid-buttonColor2">
<button
type="button"
style="background-color: transparent; border: none; padding: 0"
data-toggle="modal"
data-target="#MessageBoxModal"
onclick="ShowMessageBoxWithMessage_<%= ucMessagebox.ClientID%>('Confirmación', '¿Está seguro que desea eliminar la tarea?','DeleteTaskReports','<%# Item.ReportDetailId.ToString() %>')">
<i class="material-icons prefix">delete</i>
</button>
</span>
</div>
</ItemTemplate>
</telerik:GridTemplateColumn>
How can I access those buttons in order to write in the code behind something like: buttonName.Enabled = false;
Please! This is driving me crazy!
Thank you guys!
May be this will help you
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
Button btn = item.FindControl("img1") as Button;
btn.Enabled = false;
}
}
or
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
if ("your Condition")
{
foreach (GridDataItem dataItem in RadGrid1.MasterTableView.Items)
{
((Button)cmdItem.FindControl("btnEditReportDetail")).Visible = false;
}
}
}
You need to use FindControl to find server control that inside of Grid.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Button button = e.Row.FindControl("Button1") as Button;
button.Enabled = false;
}
I have added a search box on the Site.Master page of a website (ASP.NET) that I am developing using Visual Studio.
Problem
However I noticed that when I access default.aspx page and I click on the Search button it doesn't ReDirect (you may see below the code behind). However when I access other pages of my website the button does redirect as required.
Update
I am noticing that all button on the default.apsx page are not raising postback on default.aspx page.... on the other pages. Buttons are working fine...
Code:
SiteMaster
<body>
<form runat="server">
<asp:ScriptManager runat="server">
.......
</asp:ScriptManager>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
......
</div>
<div class="navbar-collapse collapse">
......
</div>
</div>
</div>
<br />
<div class="container body-content">
<asp:SiteMapPath ID="SiteMapPath1" runat="server">
</asp:SiteMapPath>
<div class="row">
<div class="col-md-8">
</div>
<div class="col-md-4">
<div class="input-group">
<asp:TextBox class="form-control" type="text" ID="tbSearch" width="100%" runat="server" placeholder="Search for recipes..."></asp:TextBox>
<span class="input-group-btn">
<asp:Button class="btn btn-primary" type="button" ID="btnSearch" runat="server" Text="Search Recipes" CausesValidation="False" OnClick="btnSearch_Click" ToolTip="Search Recipes" ValidateRequestMode="Disabled" />
</span>
</div>
</div>
</div>
<br />
<asp:ContentPlaceHolder ID="MainContent" runat="server">
.....
</asp:ContentPlaceHolder>
SiteMaster.cs
In the Code behind I have the following code:
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
Context.GetOwinContext().Authentication.SignOut();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
var searchText = Server.UrlEncode(tbSearch.Text); // URL encode in case of special characters
Response.Redirect("~/Results.aspx?search=" + searchText);
}
}
Default.aspx.cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Label2.Visible = true;
Label1.Visible = false;
tbPost.Visible = false;
Button1.Visible = false;
}
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
Label1.Visible = true;
Label2.Visible = false;
tbPost.Visible = true;
Button1.Visible = true;
}
if (!this.IsPostBack)
{
BindRpt();
}
}
Actually the problem was caused by an input tag....
So if any one of you will encounter this problem follow these steps:
Check any java script you have on the page
Check the page for any input tags: -
When I added disable='' in the input tag, my problem was solved.
You may also create a new page and copy to it parts of the code and check if it works correctly or not....
thats how I solved my problem
I have a Repeater binded with database data. I need to find out the Product ID binded to Label but am unable to fetch it.
Here is my Aspx page
<asp:Repeater ID="rpProducts" runat="server" OnItemCommand ="add_click" >
<ItemTemplate>
<div style="visibility: hidden">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id")%>' ></asp:Label>
</div>
<div class="col-sm-4 prdcts">
<h3>
<%# Eval("productName")%></h3>
<div class="col-sm-12 prdctbox">
<span class="AddToCrt">
<div title="Add to Cart">
<%-- <em class="fa fa-plus"></em>--%>
<asp:ImageButton ID="ImageButton1" runat="server" onclick="add_click" Height="22px"
ImageUrl="~/static/uploads/images/1_1-128.png" Width="24px"/>
</div>
</span>
<div class="imgs">
<%# Eval("productDescription")%>
</div>
<%# Eval("listingHTML")%>
<div class="row">
More
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
my codding in c# is
//void rpProducts(object sender, RepeaterItemEventArgs e)
//{
// Label l = (Label)e.Item.FindControl("Label1");
// string s = l.Text;
//}
//protected void add_Click(object sender, RepeaterCommandEventArgs e)
//{
// Label l = (Label)e.Item.FindControl("Label1");
// string s = l.Text;
//}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
Label l = (Label)e.Item.FindControl("Label1");
string s = l.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
}
Is there any way to fetch the label value?
You don't need the hidden label at all. You just need to change markup for your button a little bit.
<asp:ImageButton ID="ImageButton1" runat="server" CommandArgument='<%# Eval("id")%>' ... />
And in you codebehind you can reference the id like:
protected void Button1_Click(object sender, EventArgs e)
{
var button = (IButton)sender;
// assuming id is Int32
int id = int.Parse(button.CommandArgument);
}
Your Label1 is inside ItemTemplate so correct way to fetch the control value is
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item|| e.Item.ItemType == ListItemType.AlternatingItem)
{
Label l = (Label)e.Item.FindControl("Label1");
string s = l.Text;
}
}
I have the following code in the Page_Load method of a web form:
protected void Page_Load(object sender, EventArgs e)
{
CountrySelectButton.Click += new EventHandler(CountrySelectButton_Click);
if (HomePage.EnableCountrySelector) //always true in in this case
{
if(!IsPostBack)
BindCountrySelectorList();
}
}
The BindCountrySelectorList method looks like this:
private void BindCountrySelectorList()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(HomePage.CountryList);
var ds = nvc.AllKeys.Select(k => new { Text = k, Value = nvc[k] });
CountrySelector.DataSource = ds;
CountrySelector.DataTextField = "Text";
CountrySelector.DataValueField = "Value";
CountrySelector.DataBind();
}
And I have a LinkButton click event handler which gets the SelectedValue from the SelectList as so:
void CountrySelectButton_Click(object sender, EventArgs e)
{
//get selected
string selectedMarket = CountrySelector.SelectedValue; //this is always the first item...
//set cookie
if (RememberSelection.Checked)
Response.Cookies.Add(new HttpCookie("blah_cookie", selectedMarket) { Expires = DateTime.MaxValue });
//redirect
Response.Redirect(selectedMarket, false);
}
EDIT:
This is the DDL and LinkButton definition:
<asp:DropDownList runat="server" ID="CountrySelector" />
<asp:LinkButton runat="server" ID="CountrySelectButton" Text="Go" />
Resulting markup:
<select name="CountrySelector" id="CountrySelector">
<option value="http://google.com">UK</option>
<option value="http://microsoft.com">US</option>
<option value="http://apple.com">FR</option>
</select>
<a id="CountrySelectButton" href="javascript:__doPostBack('CountrySelectButton','')">Go</a>
END EDIT
ViewState is enabled but the SelectedValue property only ever returns the first item in the list regardless of which item is actually selected. I'm certain I'm missing something obvious but I can't find the problem; any help is much appreciated.
Thanks in advance.
Dave
You are correct that your issue stems from the jquery ui dialog... you can get around this by using a hidden field to record the value of the dropdownlist. Then in your code, reference the hidden field.
Front end could look like:
<div id="myModal" style="display: none;">
<asp:DropDownList runat="server" ID="SelectList" />
<asp:LinkButton runat="server" ID="MyButton" Text="Go" />
</div>
<input type="hidden" id="countryVal" runat="server" />
<a id="choose" href="#">Choose</a>
<script type="text/javascript">
$(document).ready(function () {
$('#choose').click(function () {
$('#myModal').dialog({
});
return false;
});
$('#<%= SelectList.ClientID %>').change(function () {
var country = $(this).val();
$('#<%= countryVal.ClientID %>').val(country);
});
});
</script>
Then your code behind:
var selected = countryVal.Value;
Wrap the MyButton.Click+=... statement inside (!IsPostBack) like
if(!IsPostBack)
{
MyButton.Click += new EventHandler(MyButton_Click);
BindSelectList();
}