I have a div like below I want to do some work when I click div:
with jQuery click I want to show another div that contain ListView (that must show messages) and by another click hide that div.
with C# click event I want to get Messages and bind to ListView
jQuery works but C# event does not work.
Another problem is that if I click div for second time the div will hide and I don't want bind messages
How should I do these works?
<div id="div1" class="Message" runat="server" onclick="ShowMessage">
jquery code:(this works)
$('#div1').click(function (e) {
e.stopPropagation();
if ($("#div2").is(":hidden")) {
$("#div2").show(500);
}
else {
$("#div2").hide(500);
}
});
and my code behind:(does not work)
protected void ShowMessage(object sender, MouseEventArgs e)//this will bind messages to ListView inside of div2
{
using (MYEntities en = new MyEntities())
{
///...
}
}
If you are using button then javascript click event of the button will get call and at the end just write return true then it will go to ServerSide click event of the button.
$('#btnClick').click(function(){
// your code
return true;
}
Protected void btnClick_Click()
{
}
Related
I want to create a reusable user control that allows the user to create and remove tags.
It should have a textbox where the user can enter a tag name, and a button to submit the tag.
After sumbitting the tag, it should dynamically create a label with the tag name with a "X" button to remove it for every entered tag.
Something like this:
[ Textbox ] [Submit]
[X] Tag 1
[X] Tag 2
[X] Tag 3
The issue is that I cannot figure out how to make everything work properly.
Selector.ascx
< markup for the textbox >
< markup for the sumbit button >
<asp:Placeholder runat="server" ID="PHList" />
I'm using an asp:Placeholder to generate the dynamic controls.
Selector.ascx.cs
I need to keep track of the generated controls between postbacks.
I'm using a List<string> stored in the viewstate:
private List<string> SelectedTags
{
get
{
return (List<string>) ViewState["SelectedTags"];
}
set { ViewState["SelectedTags"] = value; }
}
When I click the submit button, I add a new tag to the SelectedTags list, and call the RefreshPlaceholder function:
void RefreshPlaceholder()
{
PHList.Controls.Clear();
foreach(var x in SelectedTags)
{
// generate a label and the "X" button, wiring it with a lambda
}
}
When I click the submit button, a new (button, label) pair is correctly generated and displayed after postback.
When I click any of the generated "X" buttons, however, I get an error because the click event fired by the dynamically generated button cannot find the sender button anymore, since it hasn't been generated yet.
If I try to generate the buttons in OnLoad, the same issue occurs, as postback events occur before Page.Load.
If I try to generate the buttons in OnInit, the ViewState has not been updated yet, so the generated list will be outdated as the SelectedTags viewstate list is not yet updated.
I can't seem to find a solution to make everything work as intended. What am I doing wrong?
Declare a List of type Buttons on OnInit method; then in RefreshPlaceHolder retrieve and loop through selected tags and add them to the List
protected override void OnInit(EventArgs e)
{
List<Button> listButtons ;
base.OnInit(e);
}
void RefreshPlaceholder()
{
listButtons = new List<Button>();
PHList.Controls.Clear();
foreach(var x in SelectedTags)
{
Button b = new Button();
b.Text=x;
listButtons.add(b);
// generate a label and the "X" button, wiring it with a lambda
}
}
i have one textbox and one button both on a gridview , when user clicks on button i want to get the textbox text and save to database then clear the text! i used code below it works fine and saves to database but cant clear the textbox why ?
protected void sendcm_Click(object sender, EventArgs e)
{
try
{
Button sendcm = (Button)sender;
GridViewRow gvrow = (GridViewRow)sendcm.NamingContainer;
int ActivityTypeID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["ActivityTypeID"].ToString());
int SourceID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["SourceID"].ToString());
TextBox tt = (TextBox)activity.Rows[gvrow.RowIndex].FindControl("cmtextbox");
if (tt.Text != "")
{
BusinessLayer.StatusComment_Table ncm = new BusinessLayer.StatusComment_Table();
ncm.Id = Convert.ToInt32(Session["ID"].ToString());
ncm.Statusid = SourceID;
ncm.Statuscommentdate = System.DateTime.Now;
ncm.Statuscommenttext = tt.Text;
ncm.Save();
tt.Text = ""; // its not working !!!!
}
}
protected void Page_Load(object sender, EventArgs e)
{
SessionLable.Text = Session["ID"].ToString();
if (!IsPostBack)
{
getData();
}
}
public void getData()
{
activity.DataSource = BusinessLayer.Activity_Table.GetByProfileData(ID, -1, activity.PageSize);
activity.DataBind();
}
You need to do this at the UI level.
Use jquery.post to call the method that saves the data.
return something back to the $.post callback to tell jquery that the post s complete,
then do something like $('#mytextfield').val('')
assuming that the text box has an ID. I am assuming this is HTML?
you might need to rebind your grid because from the code that you posted it's not clear that where are you re binding your grid.
You need to enable AjaxPostback in your page. After that, in your Page_Load logic, include the code
if(IsPostBack){...}else{...}
So you can handle the construction of UI elements depending on whether this is a fresh new view of the page or a postback (page refreshed due to user clicking the button). UI elements are sent to the browser, after that, there is no way for the server to change it except to refresh the page itself.
The manual (and the one I recommend) way is to do this via jQuery postback. As pointed out in the other answer, you'll need to setup an endpoint for the client browser to connect. After the server has done its job, return the result to the client. Then use jQuery to update the textbox.
i did this to solve my problem !
<asp:TextBox ID="cmtextbox" type="text" clientid="cmtextbox" TextMode="MultiLine" placeholder="نظر دهید..." Rows="1" style="resize:none" class="form-control" runat="server"></asp:TextBox>
<asp:Button ID="sendcm" style="margin-top:2px;" OnClick="sendcm_Click" class="btn btn-success btn-sm pull-left " OnClientClick="ClearTextbox(this)" runat="server" Text="ارسال" />
</script>
<script type="text/javascript">
ClearTextbox = function (that) {
$(that).prevUntil('div.stop', '[ClientID="cmtextbox"]').val('');
}
</script>
I'm designing a page that has an Infragistics WebImageButton.
When clicking on that button I display a confirmation box.
If user clicks "OK", postback occurs that needs to trigger my click event, but it does not.
Here is what I have:
My webimagebutton:
<td><igtxt:webimagebutton id="btnHandle" runat="server" text="Process" usebrowserdefaults="False" cssclass="bodytext">
<clientsideevents click="confirmProcess"></clientsideevents>
<RoundedCorners MaxHeight="80" ImageUrl="ig_butXP1wh.gif" MaxWidth="400" HoverImageUrl="ig_butXP2wh.gif"
RenderingType="FileImages" PressedImageUrl="ig_butXP4wh.gif" DisabledImageUrl="ig_butXP5wh.gif"
FocusImageUrl="ig_butXP3wh.gif"></RoundedCorners>
</igtxt:webimagebutton>
</td>
My client-side function:
function confirmBoarding(oButton,oEvent)
{
var strMessage = "Are you sure you want to proceed?\nIf yes, press OK, otherwise CANCEL";
if(!confirm(strMessage))
{
oEvent.cancel = true;
return false;}
}
return;
}
My click event in code-behind:
private void btnHandle_Click(object sender, Infragistics.WebUI.WebDataInput.ButtonEventArgs e)
{
String here = "I'm here";//never gets hit
}
My code-behind method never gets hit.
What am I doing wrong?
Thank's
Make sure you have wired up the event. From the markup provided and the C# code there is no evidence that the event is wired up.
I have a .aspx Webpage with a UserControl added on it.In UserControl when the LinkButton is clicked it do not Postback on first attempt. but when we click again it does the Postback and then only the page redirects don't know why?
Any idea?
In .ASPX Markup:
<asp:LinkButton ID="lnkCheckOut" runat="server"
CssClass="button orange" onclick="lnkCheckOut_Click">Checkout</asp:LinkButton>
In.cs file:
protected void lnkCheckOut_Click(object sender, EventArgs e)
{
if (Session["UserID"] != null)
{
lnkCheckOut.PostBackUrl = "~/checkout.aspx?type=checkout";
//Response.Redirect("~/checkout.aspx?type=checkout");
Session["IsQuoteAdded"] = "false";
}
//if not logged in user
else
{
lnkCheckOut.PostBackUrl = "~/login.aspx?returnUrl="+HttpUtility.UrlEncode(Request.RawUrl);
}
}
When i see markup in browser(using F12 in Chrome) on first click it shows:
<a id="ctl00_ContentPlaceHolder1_shpCart_lnkCheckOut" class="button orange" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$shpCart$lnkCheckOut','')">Checkout</a>
On Second Click:
<a id="ctl00_ContentPlaceHolder1_shpCart_lnkCheckOut" class="button orange" href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ContentPlaceHolder1$shpCart$lnkCheckOut", "", false, "", "login.aspx?returnUrl=%2fNew%2fMyBox.aspx", false, true))'>Checkout</a>
Note:I am not using any UpdatePanel in the Webpage or UserControl.
Help Appreciated!
Your code is not redirecting the page it has just assigning the URL. Use below codes to rectify that.
protected void lnkCheckOut_Click(object sender, EventArgs e)
{
if (Session["UserID"] != null)
{
//lnkCheckOut.PostBackUrl = "~/checkout.aspx?type=checkout";
Session["IsQuoteAdded"] = "false";
Response.Redirect(#"~/checkout.aspx?type=checkout");
}
//if not logged in user
else
{
Response.Redirect(#"~/login.aspx?returnUrl="+HttpUtility.UrlEncode(Request.RawUrl));
}
}
In your markup, there is no PostBackUrl. So on the first click, it will actually post back to the same page, and your event handler will run.
Then, in your event handler, you are setting the PostBackUrl.
So the second time somebody clicks the link, it will post to that URL. Your code is working as designed :)
Edit: I would suggest changing to Response.Redirect, but it's hard to know exactly what your code is supposed to do.
Same issue i was facing.
I have link button in grid view. when i clicked the link button its not postback on first click ,but when i clicked again it does.
Then i check my code properly and then i find that grid view is placed in update panel hence its not postback on first click.
So i would suggest please check the same.
I have looked around and haven't found anything concrete.
Is there any tutorials on how to show/hide a form or textbox based on if a value is selected.
I have something like this Dropdown box with (Add, item1, item2,item3 ect..)
if add is selected show a form to add add with some attributes such as (First Name, last Name ect..) else it will just do an action with the selected item.
<select id="target">
<option value="option1" selected="selected">Add</option>
<option value="option2">Item1</option>
</select>
<input type="text" class="textboxclass" />
<div class="someform">
//content
</div>
Default css display property for someform class is none eg:
.someform{display:none;}
Jquery script
<script>
$('#target').change(function() {
var name = $('#target option:selected'),text(); //Item1
var id = $('#target').val(); // option2
if(id =="option2"){
//your logic for this option
//hide textbox
$('.textboxclass').hide();
$('.someform').show();
}else{
$('.textboxclass').show();
$('.someform').hide();
}
//other if else logic
});
</script>
Not tested since im on laptop without any software installed.
I would wire this up in the client-code. Handle the select's onchange event in JavaScript or jQuery and bind a handler to it. Since "Add" is the only one that will show the form, in your handler check for the value selected and if it's the value for "Add", show the form. If it's any other value, hide the form.
If you want to do this in the server code, just handle the event for the selection changed and set the visibility property of your form that way. Either way should be pretty easy.
Doing this on the client allows you to avoid coding around postbacks while removing responsibility of processing the request from the server.
if you want to do this from server side you will need to set the AutoPostBack propetry of DrowpDown list to true,
and in the SelectedIndexChanged event of DropdownList
try this,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
{
entryForm.Visible = true;
viewForm.Visible = false;
}
else if (DropDownList1.SelectedIndex == 1)
{
entryForm.Visible = false;
viewForm.Visible = true;
}
but this is not a good aproach, i will suggest to follow the answers given above, and do it with JavaScript or JQuery