aarebrot.net Frode's blog on Sharepoint and other stuff

How to get a value from a form

Posted on November 24, 2008
VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)

This may be pretty obvious to more seasoned C# web developers, but if you're fresh with web part development (like me) this may come in handy.

Last week I was working on a feedback form. The user enters in some data in an HTML form, hits the submit button, and Sharepoint sends an email to a preset email address. Problem was, I had no idea how to get the value from the POST event.

Now one of the problems is that Sharepoint puts a whole bunch of garble in from of the ID tag for each form element. So if you assign a constant value to the ID tag like this:

private const string ID_COMMENT_BODY_TEXTBOX = "txtComment";

It will end up looking something like this:

<textarea id="ctl00_SPWebPartManager1_g_6f6eeff6_028b_49bc_bfe3_dcf57b81eccf_txtComment" >

That's pretty messy. A long very unfriendly ID tag for sure. So I figured why don't we make a loop and just look for our ID tag as part of the key. That way we don't have to know the exact name, but rather just the part we named it.

foreach (string key in this.Page.Request.Form.Keys)
{
  if (key.Contains(ID_COMMENT_BODY_TEXTBOX))
    _formattedCommentBodyString = this.Page.Request.Form[key];
  else if (key.Contains(ID_COMMENT_TITLE_TEXTBOX))
    _formattedCommentTitleString = this.Page.Request.Form[key];
}

Note that you can put multiple elements in the loop, and therefore assign more then just one string in each loop (i.e. if you have 4 form elements, don't make 4 loops... stick them all in the same for each loop). The constants I'm referring to above I've assigned to the form elements that I want to retrieve the data from:

oCommentBodyTextBox = new TextBox();
oCommentBodyTextBox.TextMode = TextBoxMode.MultiLine;
oCommentBodyTextBox.ID = ID_COMMENT_BODY_TEXTBOX;
oCommentBodyTextBox.CssClass = CSS_COMMENT_BODY_TEXTBOX;
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

 

No trackbacks yet.