Hi makenzi.exc,
WebMethod arguments cannot be nullable and you can not make them optional.
So to handle this case, send argument data as serialized json object string to WebMethod.
Refer below example.
HTML
<table>
<tr>
<td>Name</td>
<td><input id="txtName" type="text" /></td>
</tr>
<tr>
<td>Age</td>
<td><input id="txtAge" type="text" /></td>
</tr>
<tr>
<td colspan="2"><input id="btnSubmit" type="button" value="Submit" /></td>
</tr>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function () {
var person = {};
person.Name = $("#txtName").val();
person.Age = $("#txtAge").val();
$.ajax({
type: "POST",
url: "Default.aspx/GetAge",
data: "{person: " + JSON.stringify(person) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Age is : " + data.d);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
Code
[System.Web.Services.WebMethod()]
public static int GetAge(Person person)
{
return person.Age ?? 0;
}
public class Person
{
public string Name { get; set; }
public int? Age { get; set; }
}