After learning how to use the page method in JavaScript and ASP.Net (VB.Net), I encountered an issue when trying to insert multiple items into a database using a gridview. Despite my efforts, there were no error messages appearing. Here is what I have so far:
Server-side code (VB)
<WebMethod()> _
<ScriptMethod()> _
Public Shared Sub SavetoDB(ByVal ans As Answers)
Dim constr As String = ConfigurationManager.ConnectionStrings("CCQTConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO tblApplicantAns (Appnr, QID, answer) VALUES(@Appnr, @QID, @ans)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@Appnr", ans.appnr)
cmd.Parameters.AddWithValue("@QID", ans.qid)
cmd.Parameters.AddWithValue("@ans", ans.ans)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Public Class Answers
Public Property qid() As String
Get
Return _qid
End Get
Set(ByVal value As String)
_qid = value
End Set
End Property
Private _qid As String
Public Property ans() As String
Get
Return _ans
End Get
Set(ByVal value As String)
_ans = value
End Set
End Property
Private _ans As String
Public Property appnr() As String
Get
Return _appnr
End Get
Set(ByVal value As String)
_appnr = value
End Set
End Property
Private _appnr As String
JavaScript (AJAX)
$(function () {
var gvDrv = document.getElementById("<%= grdQ.ClientID %>");
for (i=1; i<gvDrv.rows.length; i++)
{
var cell = gvDrv.rows[i].cells;
var q = cell[0].innerHTML;
var a = cell[1].innerHTML;
$("[id*=Button1]").bind("click", function () {
var ans = {};
ans.appnr = $("[id*=TextBox1]").val();
ans.qid = $(" + q + ").val();
ans.ans = $(" + a + ").val();
$.ajax({
type: "POST",
url: "English.aspx/SavetoDB",
data: '{ans: ' + JSON.stringify(ans) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Time is up! Exam will proceed to next module.");
window.location = "Conf_English.aspx";
}
});
return false;
});
});
}