How to add query parameters to a dopostback - c#

I have a grid view that looks generally like this
<asp:GridView ID="MyGridView"
OnSelectedIndexChanged="OtherAddressGrid_SelectedIndexChanged"
OnRowDataBound="OnRowDataBoundOther"
<Columns></Columns>
</asp:GridView>
and on OnSelectedIndexChanged I want to change the postback url to add &TAB=something so that I can change the page to the selected tab using the Request.QueryString["TAB"]. To do this I set the onclick to a postback in OnRowDataBoundOther. This is what I have so far
protected void OnRowDataBoundOther(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(MyGridView, "Select$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
}
question
How do I add custom parameters to this postback.

You can add your own select button to the Gridview that triggers the OnSelectedIndexChanged. You only have to add CommandName="select" to it in order to work. You also need to add a PostBackUrl to the button and a custom property that holds the value of TAB (in this snippet it is the row index)
<asp:Button ID="Button1" runat="server" Text="Select" CommandName="select"
data-item='<%# Container.DataItemIndex %>' PostBackUrl="~/Default.aspx?TAB=" />
You now have a button that looks something like this in HTML.
<input type="submit" name="GridView1$ctl05$Button1" value="Button"
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("GridView1$ctl05$Button1", "", false, "", "Default.aspx?TAB=", false, false))"
id="mainContentPane_GridView1_Button1_3" data-item="3" />
As you can see aspnet added an onclick function to the button because you added a PostBackUrl. That function contains the url that will be used for PostBack. All we have to do now is change that url by adding the custom property with jQuery.
<script type="text/javascript">
$(document).ready(function () {
$('#<%=GridView1.ClientID %> input[type=submit]').each(function () {
var item = $(this).attr('data-item');
$(this).attr("onclick", $(this).attr("onclick").replace("?TAB=", "?TAB=" + item));
});
});
</script>

Related

How to implement input checkbox's checked action?

In a WebForm I have an input checkbox to which I wanna apply server side action.
For example, when the checkbox is checked, I want to change some label's text.
I have tried to use on client side:
<input id="auto" name="auto" type="checkbox" data-toggle="toggle" data-on="AUTOMAT" data-off="MANUAL" <%= string.IsNullOrEmpty(Request["auto"]) ? string.Empty : "checked" %> />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:HiddenField ID="customSwitch1Change" runat="server" Value="0" />
<script>
$('#auto').click(function () {
$('#<%=customSwitch1Change.ClientID%>').val("1");
$('#form1').submit();
});
</script>
I have used this and this for the input checkbox.
On the server-side I have tried:
protected void CustomSwitch1Change(string auto)
{
if (string.IsNullOrEmpty(auto))
{
Label3.Text = $"customSwitch1 was not checked.";
}
else
{
Label3.Text = $"customSwitch1 was checked and the check value is {auto}.";
}
}
But what I've tried is not working.
What I'm doing wrong? Or is there another way to do this?
You don't need the HiddenField. If you change the jQuery to the code below it will do a form post on CheckBox change.
<script>
$('#auto').change(function () {
$('#form1').submit();
});
</script>
Then you can simply get the value in code behind with
string auto = Request.Form["auto"];

Avoid page refresh click on Button Asp.net c#

enter code here NET application, I have inserted a button that call a Javascript function (OnClick event) and a asp.net function (OnClick event)
The problem is that when I click the button, it refreshes the page.
How can I avoid the page refreshes click on asp button using javascript?
document.getElementById('pageurl').innerHTML = "tryfblike.aspx";
$('#<%= btnsave.ClientID %>').click();
$('#auth-loggedout').hide();
<asp:Button runat="server" ID="btnsave" OnClick="btnsave_Click();" Visible="true" style="display: none;" />
protected void btnsave_Click(object sender, EventArgs e)
{
objda.agentid = "2";
string currenttime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
objda.datetime = currenttime;
ds = objda.tbl_log();
}
First to call JavaScript function, use OnClientClick.
To avoid page refresh, after your function call add return false;
For example:
<asp:Button ID="btnSubmit" runat="Server" OnClientClick="btnsave_Click(); return false;" />
in java script you can use return false.
if you want prevent whole page referesh use ajax.
FirstYou can call javascrip onclick and then simply add
return false;

ASP.NET Passing asp:Repeater value to asp:Button CssClass attribute

I have a payment method repeater that contains a button. We have new button styles that need to be applied. The new button style changes based on a btnMode setting in the database which is set to a string representing a CSS class selector. The CSS works fine.
I put this in the ASPX page:
<asp:Button ID="btnEdit"
runat="server"
ClientIDMode="Static"
CssClass='<%# Eval("btnMode") %>'
Text="edit"
CommandName="ChangePaymentProfile"
CommandArgument='<%# Eval("PaymentSourceId") + "|" + Eval("AuthNetPaymentProfileId")%>' />
In the ASPX.cs
//Command Button Clicked: Change Payment Method
else if (e.CommandName.ToLower().Equals("changepaymentprofile"))
{
hdChangeYN.Value = "Y";
showAddPaymentForm();
//display billing address of selected card
hsParams.Add("CustomerId", User.Identity.Name);
hsParams.Add("PaymentSourceId", strPaymentSourceId);
DataTable dt = DbHelper.GetDataTableSp("234_accountAddress__ByPaySourceId", hsParams);
if (dt.Rows.Count > 0)
{
tbFistName.Text = dt.Rows[0]["FirstName"].ToObjectString();
tbLastName.Text = dt.Rows[0]["LastName"].ToObjectString();
inputAddress1.Text = dt.Rows[0]["Address"].ToObjectString();
inputAddress2.Text = "";
string strCountryCd = dt.Rows[0]["CountryCd"].ToObjectString();
ddlCountry_Update(strCountryCd); //Update Country & State DDL because Country can be a foreign country
ddlCountry.SelectedValue = strCountryCd;
inputCity.Text = dt.Rows[0]["City"].ToObjectString();
ddlState.SelectedValue = dt.Rows[0]["StateProvinceId"].ToObjectString();
inputZipcode.Text = dt.Rows[0]["Zipcode"].ToObjectString();
ddlCardType.SelectedValue = dt.Rows[0]["CardType"].ToObjectString();
}
}
When I load the page in the browser the <%# Eval("btnMode") %> does not get resolved to a value. I see this when I open the inspector:
<input
id="btnEdit"
class="<%# Eval("btnMode") %>"
type="submit"
name="ctl00$ctl00$ContentPlaceHolderFront$ContentPlaceHolderFront$rptList$ctl01$btnPrimary"
value=""
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl00$ContentPlaceHolderFront$ContentPlaceHolderFront$rptList$ctl01$btnPrimary", "", true, "", "", false, false))" >
It is important to point out that this attribute CommandArgument='<%# Eval("PaymentSourceId") %>' does work, and btnMode does contain valid data.
As I wrote in a comment, not all properties in Asp.Net controls can be databound. CssClass is one that cannot be databound.
To get around this, you can add an OnItemDataBound event handler to the repeater where the Button is. In the event handler you can then user the e.Item.DataItem to get the value you want and set it as the CssClass on the button. Sample code:
<asp:Repeater ID="RepeaterTest" runat="server" OnItemDataBound="RepeaterTest_ItemDataBound">
<ItemTemplate>
<div>
<asp:Button ID="TestButton" runat="server" Text='<%# Eval("someText") %>'/>
</div>
</ItemTemplate>
</asp:Repeater>
and code behind:
protected void Page_Load(object sender, EventArgs e)
{
var testData = Enumerable.Range(1, 10).Select(i => new { someText = "Button " + i.ToString() }).ToList();
RepeaterTest.DataSource = testData;
RepeaterTest.DataBind();
}
protected void RepeaterTest_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
dynamic foo = e.Item.DataItem;
((Button)e.Item.FindControl("TestButton")).CssClass = foo.someText;
}

HiddenField.ValueChanged Event not firing when changed from Javascript

UPDATE
I moved the Javascript to the ASPX site instead, and added a postback function for it. Now it works. Thanks to #orgtigger and especially #lucidgold for spending their time helping me!
Here is the update code that works!
<script type="text/javascript">
function changevalue(katoid) {
$('#<%=txtboxchosenkat.ClientID%>').val(katoid);
__doPostBack('<%= updpnlgridview.ClientID %>', '');
}
</script>
Code:
<asp:UpdatePanel ID="updpnlgridview" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtboxchosenkat" style="display:none;" runat="server" OnTextChanged="txtboxchosenkat_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:GridView ID="gridview" runat="server"></asp:GridView>
</ContentTemplate>
</asp:UpdatePane
Code-behind:
protected void hidfldchosenkat_ValueChanged(object sender, EventArgs e)
{
SqlConnection cn2 = new SqlConnection("Server=**,***,***,**;Database=******;
User Id=******;Password=******;");
SqlCommand cmd2 = new SqlCommand("SELECT * FROM tblProducts where KatID='" +
txtboxchosenkat.Text + "'", cn2);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.SelectCommand.CommandText = cmd2.CommandText.ToString();
DataTable dt = new DataTable();
da2.Fill(dt);
gridview.DataSource = dt.DefaultView;
gridview.DataBind();
}
The links (only part of code that makes links):
string line = String.Format("<li><a href='#' onclick='changevalue(" + pid + ");'>{0}",
menuText + "</a>");
Old Post
I need to update a GridView based on the value of a HiddenField. I am currently using a button to populate the GridView, but would like to do it automaticaly as soon as the value in the HiddenField changes.
But when I change the value with a javascript, then event doesn't fire.
(Same thing also happens in case of a TextBox and its OnTextChanged event.)
Not sure if this is way it's meant to work.
A Hidden field will not produce a postback (there is no AutoPostBack property), which means no postback will happen when the value of the hidden field has changed. However, when there is ANY postback from the page then OnValueChangd event will execute if a hidden field value has changed.
So you should try the following ideas:
1) Update your JavaScript for changevalue as follows:
function changevalue(katoid)
{
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid;
_doPostBack(); // this will force a PostBack which will trigger ServerSide OnValueChange
}
2) Change your HiddenField to a TextBox but set the Style="display:none;" and set AutoPostBack="true":
<asp:TextBox runat="server" ID="hidfldchosenkat"
Value="" Style="display:none;"
AutoPostBack="true" OnTextChanged="hidfldchosenkat_TextChanged">
</asp:TextBox>
This example works great for me:
JavaScript:
function changevalue()
{
$('#<%=hidfldchosenkat.ClientID%>').val("hi");
}
ASPX Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="hidfldchosenkat" runat="server" AutoPostBack="true"
ontextchanged="hidfldchosenkat_TextChanged"></asp:TextBox>
<asp:Button ID="Button1"
runat="server" Text="Button" OnClientClick="changevalue()" />
</ContentTemplate>
</asp:UpdatePanel>
C# Code-Behind:
protected void hidfldchosenkat_TextChanged(object sender, EventArgs e)
{
string x = "hi"; // this fires when I put a debug-point here.
}
Your issue could be with:
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid
You may want to try:
$('#<%=hidfldchosenkat.ClientID%>').val(katoid);
Also you should PUT changevalue() inside your ASPX JavaScript tags and not register it for every LinkButton.... so instead try the following:
protected void lagerstyringgridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Assuming the LinkButtons are on the FIRST column:
LinkButton lb = (LinkButton)e.Row.Cells[0].Controls[0];
if (lb != null)
lb.Attributes.Add("onClick", "javascript:return changevalue(this);");
}
}
You can have any event fire by doing a __doPostBack call with JavaScript. Here is an example of how I used this to allow me to send a hiddenfield value server side:
ASPX
<asp:HiddenField runat="server" ID="hfStartDate" ClientIDMode="Static" OnValueChanged="Date_ValueChanged" />
JavaScript
$('#hfStartDate').val('send this');
__doPostBack('hfStartDate');
This will call the OnValueChanged event and cause a postback. You can also set this is a trigger for an update panel if you would like to do a partial postback.

How to remove row on click on confirm message true?

I have a asp gridview. On row databound I add onclick event to view item details. I have also delete button. The problem is When I click item delete, it deletes item but also redirect to item preview page. It should not do a postback and redirect
here is my code
protected void Grid_DataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["onClick"] = String.Format("location.href='" + "/Url/page.aspx?id=" + "{0}", DataBinder.Eval(e.Row.DataItem, "Id") + "'");
}
delete button
public void GvDeleteHabit(object source, CommandEventArgs e)
{
int id= Convert.ToInt32(e.CommandName);
Delete(id);
}
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return confirm('Do you want to delete?')"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
on client side I have confirm message. So what I'm trying to achieve is when user click delete button and Yes, I need to remove onclick event from row and delete item.
if user click No stop page from loading. so user can click somewhere on row and view details of item
Try by removing javascript: from OnClientClick. It's only needed if javascript is used in the href attribute.
The problem you're running into is that even when you click "Delete" is still registers as a click event on the row, which in turn fires off the redirect. You should put your redirect into a function, and pass in the source of the click event. If the source is your button, exit the function.
onRowClick = function(source){
if (source.element.type == "button") // this may not be correct, but you get the point
return confirm('Are you sure you want to delete this item');
//do your redirect here
}
e.Row.Attributes["onclick"] = "onRowClick(this);";
AND in your HTML markup:
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return onRowClick(this);"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
Since you have onclick handler on row also, you have to basically stop the event propagation on delete button click, try this it will solve the problem.
ASPX Change
<asp:LinkButton OnCommand="Delete" title="Delete" OnClientClick="javascript:return confrimDelete(e);"
CommandName='<%# Eval("Id")%>' runat="server" ID="BtnDelete"></asp:LinkButton>
Add this method in any of your js file or on the page
function confirmDelete(){
var event = e || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
return confirm('Do you want to delete?');
}

Categories

Resources