{"Message":"Cannot convert null to a value type.","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
[WebMethod] public static string Insert(int id, string comment) { string constr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "INSERT INTO PostComment2 (Email,CommentID,Comments) VALUES (@Email,@CommentID,@Comments)"; cmd.CommandType = CommandType.Text; cmd.Connection = con; cmd.Parameters.AddWithValue("@CommentID", id); cmd.Parameters.AddWithValue("@Email", HttpContext.Current.User.Identity.Name); // cmd.Parameters.AddWithValue("@SendDate", name); cmd.Parameters.AddWithValue("@Comments", comment); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } return ""; }
<script type="text/javascript"> $(function () { $('[id*=btncomtpost]').on('click', function () { var row = $(this).closest('tr').closest('table').parent(); var comment = $(this).closest('tr').find('[id*=txtcommentpost2]').val(); var id = $(this).closest('tr').closest('table').parent().find('[id*=lblCommentID]').html(); var obj = {}; obj.id = parseInt(id); obj.comment = comment; $.ajax({ type: "POST", url: "/Home.aspx/Insert", data: JSON.stringify(obj), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $(row).find('tr').eq(0).before('<tr><td>' + comment + '</td></tr>'); $(row).find('tr').find('[id*=txtcommentpost2]').val(''); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); return false; }); }); </script>
micah says: public static string Insert(int id, string comment)
public static string Insert(int id, string comment)
public
static
string
Insert(
int
id,
comment)
Change the above with the below.
public static string Insert(int? id, string comment)
You id is passing as null so the error. Make the id as nullable type.
© COPYRIGHT 2025 ASPSnippets.com ALL RIGHTS RESERVED.