Simulate form submit with VB.NET - asp.net

I wonder if I can simulate the action of the button
(source: xonefm.com)
in this website by VB.NET code ?
http://www2.xonefm.com/hot10/index_in.aspx

From server code you could use ClientScriptManager.GetPostBackEventReference which renders out a postback event reference
heres a link on msdn http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackeventreference.aspx
heres a sample
Allows selecting gridview row without select column.
protected override void Render(HtmlTextWriter writer)
{
GridView g = GridView1;
foreach (GridViewRow r in g.Rows)
{
if(DataControlRowType.DataRow == r.RowType)
{
r.Attributes["onMouseOver"] = "this.style.cursor='pointer';this.style.cursor='hand'";
r.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(g, "Select$" + r.RowIndex, true);
}
}
base.Render(writer);
}

Is this your web site? If so, you can probably just call the click event for the button directly (assuming it causes a postback).
Are you scraping someone else's site? In that case, use a System.Net.WebClient or System.Net.HttpWebRequest object to send a similar request to the server that the browser would send if you click the button. There are two ways to find out what the request will be:
Study the source of the page in question until you understand what http request is sent when you click the button. This can be especially tricky for asp.net sites because of the hidden ViewState field.
Use something like WireShark to sniff the packet sent and work backwards from that.

Related

calling alert from code-behind

i have a dropdownlist and a listbox both asp.net controls
i am trying to prevent the user add duplciate items to listbox control
i able to block it but i want to display DIV or Alert box saying,"duplciate names are not allowed"
protected void btn_AddRecipientAction_OnClick(object sender, EventArgs e)
{
if (Convert.ToInt32(this.ddlRecipient.SelectedValue) > 0)
{
if (ddlRecipient.Text.Length > 0)
{
//var items = new System.Collections.ArrayList(this.lstRecipient.Items);
for(var i = lstRecipient.Items.Count - 1; i >= 0; --i)
{
if (lstRecipient.Items[i].Text == ddlRecipient.SelectedItem.Text)
{
lstRecipient.Items.RemoveAt(i);
**//alert("duplicate entry not allowed")
//div display the message and disappears after few seconds?**
}
}
ListItem newList = new ListItem();
newList.Text = ddlRecipient.SelectedItem.Text;
newList.Value = ddlRecipient.SelectedValue;
this.lstRecipient.Items.Add(newList);
}
}
}
alert way:
You could use this line assuming you have a ScriptManager
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),"alert","alert('duplicate entry not allowed');",true);
This, however still does a postback since the script is run when the page is loaded again after the click. A better solution is to validate in client using javascript before submitting the page.
What you want is actually two separate things.
You should be validating on in the code behind, checking for duplicates on the post back. Then, use some javascript to do the same check on the client.
You MUST check for duplicates on the server since the user may not have javascript turned on.
Wow! Please don't inject js in the page to alert the user. You should instead have a notification control that receive a dataset of messages like an array then display the messages to the user. You want to separate your concerns.
You can achieve that in js. At the server you can set the array in json in a hidden field and then at the document ready event in js read that json data, parse it and loop on the array and display you messages. If you must you can use alert to display them but you should avoid it since it's so 1990's.
But I would go beyond that. I you do all the processing and validation in javascript before it gets to the server. So you don't rely on a post back to execute your validation. So as soon as the user adds the item it's told that it's a duplicate. Then, once the list is filled by the user he could save with a ajax call or post the page and at the server you parse the list, validate it and save it. If you have to compare the list to one already persisted at the server you can do that there. SOme thing goes wrong? you add the message to the notification control.
Please think about it. Try using a framework like MVC to separate you concerns. I makes the hole thing much faster to develop and so easier to maintain.
To call some JS from the code behind you can use Page.ClientScript property and call the RegisterStartupScript() method
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Losing backward navigation in ASP.NET

I have an ASP.NET2.0 web page with a Submit button.
When the user clicks, I generate an XML file on the fly and return that as a result.
Here is the code:
protected void submitBtn_Click(object sender, EventArgs e)
{
string result = this.ProduceMyXmlResult();
this.Response.Clear();
this.Response.StatusCode = 200;
this.Response.ContentType = "application/xml";
this.Response.ContentEncoding = System.Text.Encoding.UTF8;
this.Response.Write(result);
this.Response.End();
}
The piece of code does exactly what I want. However, the browser does not recognize the XML file as a new page, so the BACK button does not take me back to my original page. Why and how can I overcome that?
The simplest way to do so, I think, would be to create a separate page that executes this code on Page_Load(), and redirect to it when the button is pressed.
The reason you have no backward navigation is because the browser is unaware the page has changed. Since the Submit button is preforming a postback, and you are returning XML data as the response to that postback, it appears to the browser as though this is just some transformation of the current page (just as though you'd, say, changed the text of a Label control).
The "correct" way to accomplish this would be with some type of HTTP handler, but I haven't the experience to suggest the proper way to do so and you already have working C# code-behind for this method.

Setting focus on postback initiated by javascript

I am working with ASP.NET doing some client side javascript.
I have the following javascript to handle an XMLHTTPRequest callback. In certain situations, the page will be posted back, using the __doPostBack() function provided by ASP.NET, listed in the code below. However, I would like to be able to set the focus a dropdownlist controls after the post back occurs. Is there a way to set this using Javascript, or do I need to rig that up some other way.
function onCompanyIDSuccess(sender, e) {
if (sender == 0)
document.getElementById(txtCompanyIDTextBox).value = "";
document.getElementById(txtCompanyIDHiddenField).value = sender;
if (bAutoPostBack) {
__doPostBack(txtCompanyIDTextBox, '');
}
}
Since you're doing a full postback, you'd need to use Page.SetFocus on the server side to get the appropriate JavaScript emitted on the next page load.
Otherwise, in a pure AJAX solution - document.getElementById('id').focus() would do the trick.
i have found the solution for this one. In the code behind event handler being called for each particular item, I call the Control.Focus() as the last line. For instance, if a dropdownlist event handler is being triggered, and the next control to get focused is the zipcode text box:
protected void ddl_state_selectedValueChanged(Object sender, EventArgs e)
{
// ... here is all my code for the event handler
txtZipCode.Focus();
}
It was much easier that I what I was trying to do. I keep trying to overcomplicate things by creating Javascript on the fly that does exactly what Microsoft is already doing for me in the Framework.

How can I do <form method="get"> in ASP.Net for a search form?

I have a search form in an app I'm currently developing, and I would like for it to be the equivalent of method="GET".
Thus, when clicking the search button, the user goes to search.aspx?q=the+query+he+entered
The reason I want this is simply bookmarkable URLs, plus it feels cleaner to do it this way.
I also don't want the viewstate hidden field value appended to the URL either.
The best I could come up with for this is:
Capture the server-side click event of the button and Response.Redirect.
Attach a Javascript onclick handler to the button that fires a window.location.replace.
Both feel quirky and sub-optimal...
Can you think of a better approach?
Use a plain old html form, not a server side form (runat=server), and you should indeed be able to make it work.
This could however be a problem if you have an out of the box visual studio master page which wraps the entire page in a server side form, because you can't nest forms.
Web forms don't have to suck, but the default implementations often do. You don't have to use web forms for everything. Sometimes plain old post/get and process request code will do just fine.
I worked on a web site that had to post to a 3rd party site to do the search on the client's web site. I ended up doing a simple Response.Redirect and passed in the search parameters through the query string like so:
protected void Button1_Click(object sender, EventArgs e)
{
string SearchQueryStringParameters = #"?SearchParameters=";
string SearchURL = "Search.aspx" + SearchQueryStringParameters;
Response.Redirect(SearchURL);
}
And on your Search.aspx page in your pageload...
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["SearchParameters"]))
{
// prefill your search textbox
this.txtSearch.Text = Request.QueryString["SearchParameters"];
// run your code that does a search and fill your repeater/datagrid/whatever here
}
else
{
// do nothing but show the search page
}
}
Hope this helps.
This function permits to submit a page using the GET method.
To submit a page using the get method you need to:
add this code Form.Method="get"; in the Page_Load method
Use this code < asp:Button runat="server" ID="btnGenerate" /> as a submit button
add rel="do-not-submit" attribute to all form elements that you don't want to include in your query string
change the codebehind logic of your page using Request.QueryString
disable the page viewstate with EnableViewState="false" (unless it's used for other purposes)
Code
$(document).ready(function(){ enableSubmitFormByGet(); });
function enableSubmitFormByGet(){
if($("form").attr("method") == "get"){
$("form").submit(function() {
$("[name^=" + "ctl00" + "]").each(function(i){
var myName = $(this).attr("name");
var newName = "p" + (i-1);
$(this).attr("name", newName);
});
var qs =$(this).find("input[rel!='do-not-submit'],textarea[rel!='do-not-submit'],select[rel!='do-not-submit'],hidden[rel!='do-not-submit']").not("#__VIEWSTATE,#__EVENTVALIDATION,#__EVENTTARGET,#__EVENTARGUMENT").serialize();
window.document.location.href = "?" + qs;
return false;
});
I would do (b) since (a) would require two round trips for a single query. Alternatively, you could disable viewstate on the page, remove any other hidden fields via javascript, and also use javascript to modify the form method from post to get. I've never done this for real, but my toy page using the included sample worked like a charm. It's arguably easier than encoding the search string and doing the get via javascript.
Actually, it sounds like you would be happier with ASP.NET MVC since this is easily doable there by simply setting the form method to GET in the view.
sample code using jquery
$(document).ready( function() {
$('input[type=hidden]').remove();
$('form').attr('method','get');
});
EDIT: It seems like you ought to be able to do the same thing server-side, too. Maybe in OnPreRenderComplete. Don't have access to Visual Studio right now to check.
I have always used Response.Redirect as it "works".
I don't think there is an optimal method.
Just use this in your .click event before the form submission:
$("#__VIEWSTATE").remove();
$("#__EVENTVALIDATION").remove();

Modifying the HTML of a page before it is sent to the client

I need to catch the HTML of a ASP.NET just before it is being sent to the client in order to do last minute string manipulations on it, and then send the modified version to the client.
e.g.
The Page is loaded
Every control has been rendered correctly
The Full html of the page is ready to be transferred back to the client
Is there a way to that in ASP.NET?
You can override the Render method of your page. Then call the base implementation and supply your HtmlTextWriter object. Here is an example
protected override void Render(HtmlTextWriter writer)
{
StringWriter output = new StringWriter();
base.Render(new HtmlTextWriter(output));
//This is the rendered HTML of your page. Feel free to manipulate it.
string outputAsString = output.ToString();
writer.Write(outputAsString);
}
You can use a HTTPModule to change the html. Here is a sample.
Using the answer of Atanas Korchev for some days, I discovered that I get JavaScript errors similar to:
"The message received from the server could not be parsed"
When using this in conjunction with an ASP.NET Ajax UpdatePanel control. The reason is described in this blog post.
Basically the UpdatePanel seems to be critical about the exact length of the rendered string being constant. I.e. if you change the string and keep the length, it succeeds, if you change the text so that the string length changes, the above JavaScript error occurs.
My not-perfect-but-working solution was to assume the UpdatePanel always does a POST and filter that away:
protected override void Render(HtmlTextWriter writer)
{
if (IsPostBack || IsCallback)
{
base.Render(writer);
}
else
{
using (var output = new StringWriter())
{
base.Render(new HtmlTextWriter(output));
var outputAsString = output.ToString();
outputAsString = doSomeManipulation(outputAsString);
writer.Write(outputAsString);
}
}
}
This works in my scenario but has some drawbacks that may not work for your scenario:
Upon postbacks, no strings are changed.
The string that the user sees therefore is the unmanipulated one
The UpdatePanel may fire for NON-postbacks, too.
Still, I hope this helps others who discover a similar issue. Also, see this article discussing UpdatePanel and Page.Render in more details.
Take a look at the sequence of events in the ASP.NET page's lifecycle. Here's one page that lists the events. It's possible you could find an event to handle that's late enough in the page's lifecycle to make your changes, but still get those changes rendered.
If not, you could always write an HttpModule that processes the HTTP response after the page itself has finished rendering.
Obviously it will be much more efficient if you can coax the desired markup out of ASP.Net in the first place.
With that in mind, have you considered using Control Adapters? They will allow you to over-ride how each of your controls render in the first place, rather than having to modify the string later.
I don't think there is a specific event from the page that you can hook into; here is the ASP.Net lifecycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx
You may want to consider hooking into the prerender event to 'adjust' the values of the controls, or perform some client side edits/callbacks.

Resources