i am making a web api to create a drive . the html code with scripts is as below:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<h2>All Drives</h2>
<ul id="drives" />
</div>
<div>
<h2>Insert New Drive</h2>
<table>
<tr>
<td>Details : </td>
<td>
<input type="text" id="details" /></td>
</tr>
<tr>
<td>Dollars Raised :</td>
<td><input type="number" id="dollarRaised" /></td>
</tr>
<tr>
<td> Donation :</td>
<td><input type="number" id="donationCount" /></td>
</tr>
<tr>
<td>Email : </td>
<td><input type="email" id="email" /></td>
</tr>
<tr>
<td>location:</td>
<td>
<input type="text" id="location" />
</td>
</tr>
<tr>
<td>Organizer:</td>
<td>
<input type="text" id="organizer" />
</td>
</tr>
<tr>
<td>Title</td>
<td>
<input type="text" id="title" />
</td>
</tr>
<tr>
<td> Starting Date:</td>
<td>
<input type="date" id="startDate"/>
</td>
</tr>
<tr>
<td> Ending Date:</td>
<td>
<input type="date" id="endDate"/>
</td>
</tr>
<tr>
<td>Phone number: </td>
<td><input type="tel" id="phone" /></td>
</tr>
<tr>
<td> Match Count:</td>
<td>
<input type="number" id="matchCount"/>
</td>
</tr>
<tr>
<td>Swab Count:</td>
<td>
<input type="number" id="swabCount"/>
</td>
</tr>
<tr>
<td>Duration</td>
<td>
<input type="number" id="duration"/>
</td>
</tr>
<tr>
<td colspan="2"> <input type="button" value="Save" onclick="Post();" /></td>
</tr>
</table>
<p id="P1" />
</div>
<h2>Here displays returned data from web api</h2>
<div id="divResult">
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/drive';
$(document).ready(function () {
// Send an AJAX request
getdrivelist();
});
function getdrivelist() {
$.getJSON(uri)
.done(function (data) {
$('#drives').html('');
// On success, 'data' contains a list of drives.
$.each(data, function (key, item) {
// Add a list item for the drive.
$('<li>', { text: formatItem(item) }).appendTo($('#drives'));
});
});
}
function formatItem(item) {
return 'Title:' + item.title + ' and Details:' + item.details + ' From: ' + item.startDate + 'To: ' + item.endDate + 'organizer' + item.organizer ;
}
function Post() {
jQuery.support.cors = true;
var source = {
'DriveID': 0,
'details': $('#details').val(),
'dollarRaised': $('#dollarRaised').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'donationCount': $('#donationCount').val(),
'location': $('#location').val(),
'organizer': $('#organizer').val(),
'endDate': $('#endDate').val(),
'startDate': $('#startDate').val(),
'matchCount': $('#matchCount').val(),
'swabCount': $('#swabCount').val(),
'title': $('#title').val(),
'duration': $('#duration').val(),
'UserID':0
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/drive",
data: source,
success: function (data) {
getdrivelist();
},
error: function (x, y, z) {
//jsonValue = jQuery.parseJSON(error.responseText);
var strResult = "<table><th>Error Message</th>";
// $.each(data, function (index, data) {
strResult += "<tr><td> " + x.responseText + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
</script>
</body>
</html>
Now when i call the post method which is shown below:
public HttpResponseMessage Post([FromBody] JObject drivedata)
{
var jsonInput = drivedata.ToString();
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Drive drive = jsonSerializer.Deserialize<Drive>(jsonInput);
if (drive.title.Equals(""))
{
var message = string.Format("Title required");
HttpError err = new HttpError(message);
HttpResponseMessage response1 = Request.CreateResponse(HttpStatusCode.BadRequest, err);
return response1;
}
else
{
if (ModelState.IsValid)
{
try
{
db.Drives.Add(drive);
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
HttpResponseMessage response = Request.CreateResponse<Drive>(HttpStatusCode.Created, drive);
//response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
when I call the post method ,on the line where I deserialize json object to Drive object it gives error like:"is not a valid value for int32" I have already tried dynamic objects,but no luck. I am Unable to de-serialize nullable int 32 type.Some properties in Drive table are int32 and nullable and I am trying to save null value in those if left empty while adding a new record.That means, when user left the field empty while entering a new record or drive. the property donationCount ="" but I want it to store null instead of being empty.but as the property is of type int32 it cannot store null and gives error