2015-03-02 17 views
-1

我正在製作一個web api來創建驅動器。與腳本的HTML代碼如下:無法反序列化可空int 32型

<!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> 

現在,當我調用交方法,該方法如下所示:

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); 
       } 
      } 
     } 

當我打電話post方法,就行了,我反序列化JSON對象驅動對象它給出了這樣的錯誤:「不是int32的有效值」 我已經嘗試過動態對象,但沒有運氣。 我無法反序列化可空int 32類型。驅動器表中的一些屬性是int32和空,我試圖保存空值,如果留空時添加一個新的記錄。這意味着,當用戶離開字段時, 輸入新的記錄或驅動器時爲空。 屬性donationCount =「」但我希望它存儲null而不是empty.but作爲該屬性的類型int32它不能存儲空,並給出錯誤

+0

確保模型中的正確值不可用。 – 2015-03-02 18:12:01

+0

它可以爲空。錯誤是在串行化int32類型的空數據時序列化json對象。 – smriti 2015-03-02 18:14:56

回答

0

您試圖將一個空字符串反序列化爲一個可空屬性。這將不起作用,因爲字符串不適合ints,並且空字符串與空值不同。 json值必須是數字或null。

根據您提供的信息,我不知道哪個屬性導致問題,但您應該能夠輕鬆地找到它自己。然後,確保使用javascript函數parseInt(str)將字符串轉換爲有效的Number對象,因爲執行您的ajax調用。它應該看起來像這樣:

var source = { 
    ... 
    someNumericValue: parseInt($('#someId').val()), 
    ... 
};