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

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


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:

  1. add this code Form.Method="get"; in the Page_Load method
  2. Use this code < asp:Button runat="server" ID="btnGenerate" /> as a submit button
  3. add rel="do-not-submit" attribute to all form elements that you don't want to include in your query string
  4. change the codebehind logic of your page using Request.QueryString
  5. 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;});