创建绑定到集合的有效操作时出错
本文关键字:操作 出错 有效 绑定 集合 创建 | 更新日期: 2023-09-27 18:10:08
我正在开发一个Asp。Net MVC应用程序,它使用Odata和LINQ处理SQL数据库上的CRUD操作。我试图通过在控制器上创建操作来删除数据库中SQL表中的所有数据,如下所示
服务器端代码
private WhiteBoardAppContext db = new WhiteBoardAppContext();
public override HttpResponseMessage HandleUnmappedRequest(System.Web.Http.OData.Routing.ODataPath odataPath)
{
HttpResponseMessage emptyMSG = new HttpResponseMessage();
switch (odataPath.Segments[2].ToString()) // kick out if the value is the same
{
case "DeleteSegment":
string Product = odataPath.Segments[1].ToString();
byte[] param = new byte[Product.Length / 2];
for (int i = 0; i < param.Length; i++)
{
param[i] = Convert.ToByte(Product.Substring(i * 2, 2), 16);
}
Product = System.Text.Encoding.ASCII.GetString(param);
using (db)
{
var SegmentToDelete = from c in db.tblItems
where c.Product == Product
select c;
foreach (tblItem cr in SegmentToDelete)
{
db.tblItems.Remove(cr);
}
db.SaveChanges();
}
return emptyMSG;
case "DeleteAll":
using (db)
{
var itemsToClear = from c in db.tblItems
select c;
foreach (tblItem cr in itemsToClear)
{
db.tblItems.Remove(cr);
}
db.SaveChanges();
}
return emptyMSG;
default:
return base.HandleUnmappedRequest(odataPath);
}
}
客户端代码使用Knockout JS
self.deleteAll = function () {
var conf = confirm("Are you sure you want to delete all?");
if (conf == true) {
$.ajax({
url: '/odata/Items/DeleteAll'
});
}
}
当我给一个按钮分配click时,它没有像我想要的那样工作,而是通过我显示如下错误
GET http://localhost:57044/odata/Canadiancrudes/DeleteAll 500 (Internal Server Error)
Invalid action detected. 'DeleteAll' is not an action that can bind to 'Collection([WhiteBoardApp.Models.Item Nullable=False])'.
简单错误,自己修复如下
self.deleteAll = function (item) {
var conf = confirm("Are you sure you want to delete all?");
if (conf == true) {
$.ajax({
url: '/odata/Items('+item.id+')/DeleteAll'
});
}
}
-
你需要在模型生成器中定义动作DeleteAll,为什么它是动作而不是函数?如果一个方法有副作用,那么它就是动作,或者函数。
ODataConventionModelBuilder builder=new ODataConventionMocelBuilder builder.EntitySet<Item>("Items"); ActionConfiguration DeleteAll = modelBuilder.EntityType<Item>().Collection.Action("DeleteAll ");
-
用POST方法调用它:
POST ~/Items/DeleteAll
下面是一个动作示例,可能会对您有所帮助https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataActionsSample/.
注意:在你发布的错误信息中,DeleteAll跟在Canadiancrudes后面,但是js代码显示它应该跟在Items后面。