1
votes

Im in asp.net and I already have a form that utilizes runat="server". I created another form on the page and I have a method in code behind that I need to run on an onclick event.

Since I already have one form on the page, I can't use an asp:button with runat="server"

What's the best way to get my method to fire using an onclick?

Here's my code behind:

    protected void requestSong_Click (object sender, EventArgs e)
{

    var artist = Request.Form["artist"].ToUpper();
    var song = Request.Form["song"].ToUpper();
    var song_Request = artist + " - " + song;

    SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
    con2.Open();
    SqlCommand cmd2 = new SqlCommand("insert into SONGS values (@REQUESTED_SONGS)", con2);
    cmd2.Parameters.AddWithValue("REQUESTED_SONGS", song_Request);

    cmd2.ExecuteNonQuery();

Here's my aspx:

    <form id ="songRequest">
     <p style="color:greenyellow"> Request a song</p>
      <input type="text" placeholder="Artist" name="artist" id="artist" />
      <input type="text" placeholder="Song Title" name="song" id="song" />
      <button class="button" onclick="" id="requestSongButton" name="Submit">Submit</button>
    </form>
1
You cannot have multiple forms. - VDWWD
The 2nd form is not an asp.net form, it's an html form - user9175041
That does not matter. You cannot have nested forms. - VDWWD
Any suggestions on how to accomplish what Im asking then? I dont need it to be a form, but I do need to take the text from an input and send it to my method and submit the method - user9175041
You can place as many buttons and contrrols on a page you want and only read the ones you need in requestSong_Click - VDWWD

1 Answers

0
votes

You can use the approach outlined below to fire code-behind method on clicking the button in second client-side form.

  • Make sure that you have asp:ScriptManager included in your page just after the first form tag ( this is very important else this approach will not work)
  • Include the JavaScript code given below in your page. In this script, __doPostBack method is being called which is a standard JavaScript function used by asp.net framework to post back on control events like on button click. This function will only be available if you include asp:ScriptManager in your page.
  • Change the markup of the button in client-side form so it has an onclick attribute set
  • In your, code-behind in Page_Load event check for the parameters __EVENTTARGET and __EVENTARGUMENT and call the method requestSong_Click passing null for both its parameters ( note: you must not be using sender or e in your button click else this will not work)

JavaScript code to include in page

<script type="text/javascript">
    function postBack(btn) {
         //get data you want to pass to code-behind
         var artist = document.getElementById("artist").value;
         var song = document.getElementById("song").value;
         var arguments = "saveToDb" + "|" + artist + "|" + song;

        __doPostBack('requestSongButton', arguments);
        //you can pass more arguments using a comma-delimited or pipe-delimited list of values
        //to the second parameter in above method
    }
</script>

Markup needed for button in client-side form

<button class="button" onclick="" id="requestSongButton" name="Submit" 
                          onclick="doPostBack(this); return false;">Submit</button>

C# code-behind to handle submit by client-side form button

protected void Page_Load(object sender, EventArgs e)
{
  if (Page.IsPostBack)
     {
       if (Request["__EVENTTARGET"] == "requestSongButton" && 
                Request["__EVENTARGUMENT"].IndexOf("saveToDb") = 0)
        {
          //code that executes on click of requestSongButton in second form
           requestSong_Click(null, null);
        }
     }
}

C# code to get posted values for client-side form button postback

protected void requestSong_Click(object sender, EventArgs e) {
   string artist;
   string song;

   //you must always pass null for e and sender if posting from client-side form button
   if (sender == null && e == null) {
    var arguments = Request["__EVENTARGUMENT"];
    if (arguments != null && arguments != String.Empty) {

     //split the | delimited string to an array
     Dim argumentsArray as String() = arguments.Split(New Char() {
      "|"
      c
     });

     //now get values of artist textbox and song textbox
     //note that artist index is 1 and soung index is 2
     //due to the sequence in which we populated arguments
     //in client-side JavaScript doPostBack function
     artist = argumentsArray[1];
     song = argumwentsArray[2];
    }

   } else {
    artist = Request.Form["artist"].ToUpper();
    song = Request.Form["song"].ToUpper();
   }
   string song_Request = artist + " - " + song;

   SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
   con2.Open();
   SqlCommand cmd2 = new SqlCommand("insert into SONGS values (@REQUESTED_SONGS)", con2);
   cmd2.Parameters.AddWithValue("REQUESTED_SONGS", song_Request);

   cmd2.ExecuteNonQuery();

  //more of your code follows