protected void Page_Load(object sender, EventArgs e) { Student student; // Set the content type Response.ContentType = "text/plain"; Response.ContentEncoding = Encoding.UTF8; // POSTed data student = new Student() { Name = Request.Form["name"], Age = int.Parse(Request.Form["age"]) }; if (InsertStudentIntoDB(student)) { Response.Write(OutputValues(student)); } else { // Return error string as "error : some error message" Response.Write(OutputError("failed to insert student with name {0}", student.Name)); } } private bool InsertStudentIntoDB(Student student) { SqlConnection connection; SqlCommand command; int recordsAdded; bool result = false; connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString); command = new SqlCommand("INSERT Student(Name, Age) VALUES(@Name, @Age)", connection); command.Parameters.AddWithValue("@Name", student.Name); command.Parameters.AddWithValue("@Age", student.Age); using (connection) { connection.Open(); recordsAdded = command.ExecuteNonQuery(); if (recordsAdded > 0) { command.CommandText = "SELECT @@IDENTITY"; student.Id = Convert.ToInt32(command.ExecuteScalar()); // Don't cast with (int) result = true; } } return result; }