I'm currently working on a website project and I'm almost done, except that I need to get my searching to work.
I would like it to work like this: On my masterpage there is a asp:textbox and a asp:button. When I type in a search word and click on my button I would like it to redirect to a search.aspx page - The problem is, that I don't know how to do that. I only got the method and it looks like this
public DataTable Search(string Keyword)
{
return db.GetData(
"SELECT fldTitle, fldLang, fldCode from tblSnipets LIKE #1",
"%" + Keyword + "%");
}
From there I don't know what to do.
Using classic ASP.NET and PostBack event without any patterns it will look like this:
1 - Add an event handler to the button click event.
<asp:Button id="Button1" Text="Search" OnClick="SearchBtn_Click" runat="server"/>
2 - Add SearchBtn_Click handler to the code behind file of your page and do a redirect to your Search page.
it will look like this:
void SearchBtn_Click(Object sender, EventArgs e)
{
}
3 - In this event handler write code that will redirect to your Search.aspx with parameters of your search criteria:
Response.Redirect("~/Search.aspx?criteria=" + Server.HtmlEncode(myTextBox.Text));
or close to this statement (check the MSDN)
4 - On the Search.aspx code behinf page in the Page_Load handler catch the parameters and call your method to get the data.
This is not the best solution, but it should work.
Related
I'm working with ASP.NET webforms and I'm wondering if it is possible to change/ignore the PostBackUrl so it won't change pages.
My button:
<asp:Button ID="continuebtn" OnClick="Continuebtn_Click" runat="server" PostBackUrl="~/client/profile.aspx" CssClass="btn btn-success btn-sm" Text="Continue"/>
And the OnClick function is:
protected void Continuebtn_Click(object sender, EventArgs e)
{
//some code
if(condition == false)
//change the url from PostBackUrl so it won't change pages
else
//keep the current Url
}
I've tried :
continuebtn.PostBackUrl = "";
continuebtn.Attributes["PostBackUrl"] = "return false";
continuebtn.Attributes.Remove("OnClick");
continuebtn.Attributes.Add("OnClick","return false");
continuebtn.OnClientClick = "return false;";
add return; to if
I tried to remove the PostBackUrl from the button and add it from the code behind with continuebtn.PostBackUrl = "~/client/profile.aspx" but it didn't work either.
There are two big reasons to use post-back URL in place of say using a code behind click event and say then response.Redirect("some web page").
First up, post-back url passes the previous page!!!!!
So, if you have say a text box and a button like this: (or evne a grid view)
Now you can use code behind to jump to the next page, or you can use/set/have post-back url set.
If you use post-back URL. Then you don't need to write a code behind stub, and you ALSO get use of previous page in the next page on-load event (you ONLY can pick up previous page in load - first time).
eg:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
TextBox tbox;
tbox = Page.PreviousPage.FindControl("TextBox1");
Debug.Print("Text box = " + tbox.Text);
TextBox1.Text = s;
}
}
}
so post-back url = a great way to pass/get at/use the previous page values with find control. Now if you not needing to do this, then you probably should not use post-back URL, since you are bulking up the payload for the next page (it will contain the current page, and you have as noted use of "previous page". However, it is a fantastic way to avoid parameters and/or cluttering up session() just to pass a bunch of values. Just use post-back URL and then like "magic" then previous page can be used. if you don't use post-back URL then previous page is null and not valid.
And if you place two buttons on the page? Can you set postback url? Sure you can set that control, text box or do anything you like - but do keep in mind that the code behind is running AFTER a post-back, and it will of course be too late to change a button that CAUSED the post back.
So, you can certainly do this in button2 click even to change button1:
protected void Button3_Click(object sender, EventArgs e)
{
Button1.PostBackUrl = "";
}
So in above, button3 click event and code behind wiped out the post-back URL of button one. Or we can of course set the url to anything we want.
Now, the code behind is done, page is rendered and THEN sent back down to the browser with the above change. If user hits button1, then no postback url exists - we blew it out with the above code.
However, in the SAME button event? no, it is too late to change or modify the post-back.
In that case, and if you need "conditional" jump? Then you need to delete and remove the post-back url, and simply put the logic you need to determine the ya, or nay jump based on the code behind for that click event.
HOWEVER - and a BIG WHOPPER however? If you JUST use a response.Redirect("some web page") in that code behind, then you DROPPIGN THE MAIN reason as to why the developer used post-back URL in the first place. That main, big, huge, large reason is that post-back URL gives the next page in line FULL USE of the previous page values with "previous page". If you do NOT use post-back URL, then you can't use previous page to pass all those values and inspect and get and grab control values from the previous page.
So what if you really did need the "abilities" that post-back URL provides (that ability of course is "previous" page in the next page load!
In that case, then you have to use Server.Transfer() in that code stub to get use of previous page in the next page that loads.
So, regardless:
You can't change post-back URL in the same button code event - it is too late.
If you are going to then put the logic in the code event? Then be VERY VERY aware that if you use a response.Redirect("some web page"), then you may VERY well be breaking the functionally of why in the first place the developer used post-back url (to have use of "previous page".
Your suggested idea to modify client side the post-back url in one button click, and then do a js "click" of that button you just changed the post-back url should also work (good idea!!!).
But, I would thing that just using a code behind stub in the click event, and then the code can choose to navagate or jump to the next page based on that code? Right?
However, if you do that, then you will break the "features" of post-back URL in pasing page prevous.
In that case? Then you need to use a server.Transfer("to next web page") in place of response.Redirect("to next web page), since a server.Transfer will give you use of "page previous" in the next page load event JUST LIKE post-back URL does!
Of course with a server.Transfer, you will note that the web page URL does not change or update - and this is a fall out of having to do this. (and may, or may not matter to you).
Coding a page in asp.net webforms, I put a button and textbox in site.master file.
I want to do a specific action (defined in a method) when I click in button, so I put this method in site.master.cs. This method, besides other things, take the value of textbox.
I can´t reach the method when I am clicking in it.
Am I coding it in a proper way?
Are there another way to do it?
This is the relevant code.
site.master
<input id="mailListaD" type="text" value="Introduce tu Email…" runat="server"
onfocus="this.value=(this.value=='Introduce tu Email…')? '' : this.value ;" />
<asp:Button id="news_go" Text="GO" OnClick="listaDistribucion_Click" runat="server"/>
site.master.cs
protected void listaDistribucion_Click(object sender, EventArgs e)
{
string query = "INSERT INTO listaDistribucion VALUES(''," + mailListaD.Value +")";
ExecuteQuery(query);
Close();
}
The error when I compile the proyect is:
error CS7036: There is no argument given that corresponds to the required formal parameter 'sender' of 'SiteMaster.listaDistribucion_Click(object, EventArgs)'
Try generating the event from the IntelliSense, delete the event that is attached to the button and then write OnClick=.. when intellisense appears click Create New Event and in the code behind you get an event that has the name of the id of the button and onclick appended to it.
Also check if you have the correct code behind page in your masterpage in the first line above CodeBehind="MyPage.aspx.cs", check if the name of your code behind is correct.
i have a page where on click of a button, a javascript function runs. It then aggregates some data and places the data on a hidden field in this page. It then opens a new window. This new window picks up this aggregated data like so :-
$('#accepted').val(window.opener.$('#accepted').val());
where accepted is the hidden field in both parent and child window (no runat="server" was used). The issue now is that i require this data to databind two grids. Currently I've done a doPostback on both grids, but what i really want to do is doPostback for the form once and handle the databinding the PageLoad event. So two questions :-
1) How do i doPostback the form?
2) How do i do this while still being able to differentiate from the actual form submission?
To post the form you should just be able to add a call to __doPostback in your javascript, after the accepted field is set. You can use the EventTarget and EventArgument parameters of the __doPostback to control the binding in your grid.
So, you could put this in your js:
__doPostback('rebindGrid', '');
and then this in your page load event:
if (Request.Form["__EVENTTARGET"] == "rebindGrid")
{
//....Do so stuff
}
In order to tie it in more directly with the postback model I wrap mine with some C#
C# Extension Method
public static string GetPostBackLink (this Control c, string argument = "") {
return c.Page.ClientScript.GetPostBackEventReference(ctl, argument, true) + ";";
}
ASPX
<asp:LinkButton id="lnkDoThis" runat="server" onclick="lnkDoThis_Click"
style="display: none;"></asp:LinkButton>
<asp:HiddenField id="hdnParamHolder" runat="server" />
JS
function DoSomething(param) {
$("[id$='hdnDealTemp']").val(param);
<%= lnkDoThis.GetPostBackLink() %>
}
CodeBehind
protected void lnkDoThis_Click (object sender, EventArgs e) {
var myParam = hdnParamHolder.Value;
// Do server actions here
}
As for the opening in a second window ... I am not sure I follow when you want this to happen? If it is after the postback you will need to read from the hdnParamHolder control when the page reloads.
I have multiple asp:button that I created dynamically with jQuery.
For each of them, I have OnClick="ibtn_Click" .
But on the code behind, I have to manually register each one of them on Page_Load..like.. button.Click += new EventHandler(this.ibtn_Click); .
Is there a way I can register this handler automatically? Or is it possible to register it with ajax jquery?
Thanks!
You can't add ASP.NET web controls in the client's browser. ASP.NET transforms those <asp:button> tags into regular HTML, something like this:
<input type="submit" name="Button1" value="Ok" id="Button1" />
When a user clicks one of these submit controls, the browser sends a POST request, which includes the button's name as part of the posted data (which you can access via the Form collection in ASP.NET):
if (this.IsPostBack && Request.Form["Button1"] != null) {
// do something if the user clicked Button1
}
ASP.NET automatically binds server control clicks to the methods specified in the OnClick attribute. It calls the method after Page.Load completes (for the gory details, see "ASP.NET Page Life Cycle Overview").
If you're adding the buttons on the client, you can do all this yourself. For example you could "bind" the dynamically generated button in Page_PreRender:
protected void Page_PreRender(object sender, EventArgs e) {
if (this.IsPostBack && Request.Form["Button1"] != null) {
// Call another method on the page
}
}
Finally, in this day and age, if it's appropriate, you should definitely consider just calling page methods via jQuery's ajax. See this excellent Encosia article for an introduction to that technique.
Is your purpose of generating dynamic asp.net buttons to call code behind?
you can generate html "Submit" button (type=submit) and call webMethods from javascript.
The webmethods are than redirected to you c# code behind
Is there a way to click a link programatically, so that it has the same effects as if the user clicked on it?
Example:
I have an ASP.NET LinkButton:
<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass">Export</asp:LinkButton>
I have a link on a sidebar directing to the .aspx page that has this linkbutton on it. For various reasons I can't have the code for the LinkButton executed until the page has refreshed -- so I am looking for a way to force-click this LinkButton in my code once the page is completely loaded. Is there a simple/doable way to accomplish this? If it involves triggering an event, please provide a code sample if you can. Thanks.
Triggering a click event programatically on a link will trigger the “onclick” event, but not the default action(href).
And since linkbuttons come out as hrefs, so you could try doing this with Javascript.
var lnkExport = document.getElementById('<%= lnkExport.ClientID %>');
if(lnkExport){
window.location = lnkExport.href;
}
I certainly think that, there is a design and implementation flaw which forces you to conclude as you described.
Well, invoking the click event means nothing but executing the event registration method.
So, the worst suggestion I can think of is, just call the function at what point you want to happen the click event like,
lnkExport_Click(lnkExport, new EventArgs());
Rashack's post show's how to do it. You can just do it in javascript.
function ClickLink() {
document.getElementById('').click();
}
If you want this to fire after some other event, you can add code in c# to add a call to that function on the client side when the page loads.
Page.ClientScript.RegisterStartupScript(
this.getType(),
"clickLink",
"ClickLink();",
true);
I'm not sure why you'd need your page to load if you're just wanting to programmatically click that link. I'd recommend using Response.Redirect() on the server side to redirect them to that page. Not sure if there are other extenuating reasons this simple approach won't work...
--Matt
If i understand what you're saying:
<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass" onclick="lnkExport_Click">Export</asp:LinkButton>
then in your codebehind or whenever call the following when you need to...
lnkExport_Click( null, null );
and make sure you've got lnkExport_Click wired up.
protected void lnkExport_Click( object sender, EventArgs e )
{
//DO Whatever here
}
<button onclick="document.getElementById('<%=this.lnkExport.ClienID%>').click()">
click me</button>