I have a problem code. like this
View
<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 controller
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 service
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 controller
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";
}
}
The result is always show alert add fail. Seems to be json can't post to MVC controller. Please help thank you so much.
ColorDB
public partial class ColorDB
{
public int Id { get; set; }
public string Color { get; set; }
}
update:
I changed AddColor controller code.I also tyr to add ColorDB color = new ColorDB();
and color.Color = "testColor";
The value can insert to db but ColorDB col
also null.The problem seems to Mvc Controller can't Receive ajax data.
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";
}
}