views:

47

answers:

2

Hi, I am new to c#/.net and just switched over to it from classic asp(yesterday).

I am trying something very basic to begin with. I have a static form with about 20 questions (texts/textarea/checkbox/dropdown/radio) and it posts to a post page with a submit button.

I need the post page to gather the answered questions and write them to a sql db which has 1 column per question.

I did this by requesting every single form object and checking if it was null/empty and if not then putting it into a variable then I created a stored procedure and passed the 20 parameters, which inserts the record.

My question is: Is there a way that .net does this automatically? For example, .net maintains state vs classic asp I used to have to write the code to do that. I would like to be able to call something that gets the answers in an array or list and then write it to the db. What about Linq to SQL?

Thanks for your help,

+1  A: 

You will have controls on your aspx page, one per question. You still need to grab the value from each control in your postback code, and assign it to the parameter on the stored proc, or insert a row with all the parameters.

Linq to SQL can be used, but you still need to grab the values and assign to your table object.

Below is sample pseudo code, where dataContext is your linq2sql class, and the columns in your table are called q1, q2. txtQ1 is a asp:textbox and dropDownQ2 is asp:dropdownlist.

var row = new Questionnaire();
row.q1 = txtQ1.Text;
row.q2 = dropDownQ2.SelectedValue;
// etc
dataContext.Questionnaires.Insert(row);
dataContext.SubmitChanges();
Mikael Svenson
A: 

You'll still need to pull things from the UI one at a time. Placing them into an array or dictionary or something is fine so you don't have to deal with 20 variables, but as far as I'm aware you'll need to do something like:

var Answers = new Dictionary<string, string>();
Answers["firstName"] = tbxFirstName.Text;
Answers["lastName"] = tbxLastName.Text;

Linq to SQL (or EF + Linq to Entities) substitutes for the stored procedure/database access part. If you choose to use one of these, you can simplify the above. Linq to SQL can generate an Answers class for you based on your Answers database table -- at that point, you can instead do something like this:

using (var context = new QuestionAnswerContext()) {
    Answers userAnswers = new Answers();
    userAnswers.FirstName = tbxFirstName.Text;
    userAnswers.LastName = tbxLastName.Text;

    context.Answers.Insert(userAnswers);
    context.Answers.SubmitChanges();
}
Peter Leppert
I used Mikael's suggestion because I am not too familiar with Dictionary and it seemed simple enough to make a class etc etc.I used LINQ to SQL to exec a stored procedure that was passed the 32 values of the form row.q1 ... row.q32 then submitchanges()Thanks for your help.
Antoni