我有一個問題代碼。 這樣asp.net mvc使用angularjs發佈json類型到控制器插入數據庫
查看
<div ng-app="MyPct4" ng-controller="ajaxCtrl">
<div>
<table>
<tr>
<td><b>pls input Color</b></td>
<td><input type="text" ng-model="InputColor" /></td>
</tr>
</table>
<input type="button" value="save" ng-click="AddUpdateColor()" />
</div>
</div>
Angularjs控制器
var ptc4 = angular.module("MyPct4", []);
ptc4.controller('ajaxCtrl', function ($scope, myService) {
$scope.AddUpdateColor = function() {
var newColor = { Color: $scope.InputColor };
var getData = myService.AddColor(newColor);
getData.then(function (msg) {
alert(msg.data);
}, function() {
alert("error")
});
}
}
Angularjs服務
ptc4.service("myService", function ($http) {
this.AddColor = function (newColor) {
var response = $http({
method: "post",
url: "/Practice/AddColor",
data: JSON.stringify(newColor),
dataType: "json"
});
return response;
}
}
MVC控制器
private TestDBEntities2 db = new TestDBEntities2();
public string AddColor(ColorDB color)
{
if (color != null)
{
db.ColorDB.Add(color);
db.SaveChanges();
return "add success";
}
else
{
return "add fail";
}
}
結果總是顯示警告加載失敗。 似乎是json無法發佈到MVC控制器。 請幫助非常感謝。
ColorDB
public partial class ColorDB
{
public int Id { get; set; }
public string Color { get; set; }
}
更新: 我改變AddColor控制器code.I也TYR添加ColorDB color = new ColorDB(); and color.Color = "testColor";
值可以插入到數據庫,但ColorDB col
也null.The問題似乎MVC的控制器不能接收數據阿賈克斯。
public string AddColor(ColorDB col)
{
ColorDB color = new ColorDB();
color.Color = "testColor";
if (color != null)
{
db.ColorDB.Add(color);
db.SaveChanges();
return "add success";
}
else
{
return "add fail";
}
}
你有甚至嘗試調試代碼?你的顏色參數可能是空的,因爲你要發送一個字符串,並期待一個複雜的對象。 – jpgrassi