2011-03-07 24 views
0

我有以下的JavaScript。傳遞JSON到控制器的行動問題

問題是,如果我在表格「成分」中輸入一行,但是在seralising到我的C#對象後,我得到2行中的控制器行爲。但第二個對象是null?

我檢查了JavaScript和變量「CNT」是1不是2

爲什麼會是這樣?

馬爾科姆

[代碼]

$("#Save").click(function() { 
var title = $("#recipetitle").val(); 
var category = $("#category").val(); 
var preptime = $("#prepTime").val(); 
var preptimeperiod = $("#lstPrepTime").val(); 
var cooktime = $("#cookTime").val(); 
var cooktimeperiod = $("#lstCookTime").val(); 
var rating = $("#rating").val(); 
var method = $("#method").val(); 

var jsontext = '{ "RecipeTitle": "' + title + '",'; 
jsontext += '"CategoryID":' + category + ','; 
jsontext += '"PrepTime":' + preptime + ','; 
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",'; 
jsontext += '"CookTime":' + cooktime + ','; 
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",'; 
jsontext += '"Rating":' + rating + ','; 
jsontext += '"Method":"' + method + '",'; 

var ing = ""; 
var cnt = 0; 
$("#ingredients tr.ingredientdata").each(function() { 
    if ($("td.ingredient", this).text() != "") { 
     ing += '{ "IngredientName": "' + $("td.ingredient", this).text() + '",'; 
     ing += '"Units": ' + $("td.units", this).text() + ','; 
     ing += '"Measure": "' + $("td.measure", this).text() + '"} ,'; 
    } 
    cnt = cnt + 1; 
}); 
alert(cnt); 
if (ing != "") { 
    jsontext += '"Ingredients": ['; 
    ing = ing.substring(0, jsontext.length - 1); 
    jsontext = jsontext + ing; 
    jsontext += ']'; 
} 
jsontext += '}'; 

var json = eval('(' + jsontext + ')'); 
//var json = { Field: 1 }; 

$.ajax({ 
    url: "/Recipe/Save", 
    type: "POST", 
    dataType: 'json', 
    data: JSON.stringify(json), 
    contentType: "application/json; charset=utf-8", 
    success: function() { 
     //alert("DONE!!"); 
    } 
}); 

}); [/ code]

回答

1

我會推薦你​​的javascript的重構,因爲它會幫助你更容易地識別錯誤。同時用FireBug結賬實際發送給控制器的JSON請求:

$("#Save").click(function() { 
    var ingredients = $('#ingredients tr.ingredientdata').map(function(index, element) { 
     return { 
      ingredientName: $('td.ingredient', element).text(), 
      units: $('td.units', element).text(), 
      measure: $('td.measure', element).text() 
     }; 
    }); 

    var json = { 
     RecipeTitle: $('#recipetitle').val(), 
     CategoryID: $('#category').val(), 
     PrepTime: $('#prepTime').val(), 
     PrepTimePeriod: $('#lstPrepTime').val(), 
     CookTime: $('#cookTime').val(), 
     CookTimePeriod: $('#lstCookTime').val(), 
     Rating: $('#rating').val(), 
     Method: $('#method').val(), 
     Ingredients: ingredients 
    }; 

    $.ajax({ 
     url: '/Recipe/Save', 
     type: 'POST', 
     dataType: 'json', 
     data: JSON.stringify(json), 
     contentType: 'application/json; charset=utf-8', 
     success: function() { 
      //alert("DONE!!"); 
     } 
    }); 
}); 
相關問題