ExtJS 6.0单字段更新失败求助(附代码及报错信息)
相关代码
Store 代码
Ext.define('Movie.store.RentalStatusStore', { extend: 'Ext.data.Store', alias: 'store.status', storeId: 'status', requires: [ 'Movie.model.RentalModel' ], constructor: function(cfg) { var me = this; var type = Ext.util.Cookies.get("type"); if(type==1){ var id = 0; }else{ var id = Ext.util.Cookies.get("id"); } cfg = cfg || {}; me.callParent([Ext.apply({ autoLoad: true, model: 'Movie.model.RentalStatusModel', remoteSort: true, pageSize: 5, proxy: { type: 'rest', enablePaging: true, api: { create: 'https://localhost:44369/Movies/Addstatus', read: 'https://localhost:44369/Movies/Getstatus/'+id, update: 'https://localhost:44369/Movies/Editstatus', destroy: 'https://localhost:44369/Movies/Deletestatus' }, reader: { type: 'json', totalProperty: 'TotalCount', headers: { 'Accept': 'application/json' } }, writer: { type: 'json', } } }, cfg)]); } });
编辑状态的 Controller 代码
var ref="123"; var store1 = Ext.create('Movie.store.RentalStatusStore', {}); store1.load({ scope: this, callback: function (records, operation, success) { var record1 = store1.findRecord('refs', ref); console.log(record1) record1.set('Transaction_status', text); store1.sync(); } })
Web API 代码
[Route("Movies/Editstatus/{movie}")] [EnableCors("*", "*", "*")] [System.Web.Http.AcceptVerbs("Delete", "Post", "Get", "Put")] [System.Web.Http.HttpPut] public IHttpActionResult EditMovie(Movie_transaction movie) { if (!ModelState.IsValid) { return BadRequest(ModelState); } using (var ctx = new MyEntity()) { var existmovie = ctx.Movie_transaction.Where(s => s.Trans_id== movie.Trans_id).FirstOrDefault(); { existmovie.Transaction_status= movie.Transaction_status; ctx.SaveChanges(); } } return Ok(movie); }
报错信息
{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"Non-static method requires a target.","ExceptionType":"System.Reflection.TargetException","
{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at MovieRentals.Controllers.MoviesController.EditMovie(Movie_transaction movie) in C:\Users\Admin\source\repos\MovieRentals\MovieRentals\Controllers\MoviesController.cs:line 381\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.
b__2(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker. d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult. d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher. d__15.MoveNext()"}
问题分析与修复方案
核心问题定位
- 路由配置错误:Web API路由
[Route("Movies/Editstatus/{movie}")]中的{movie}参数与接收的实体对象冲突,导致模型绑定失败,触发Non-static method requires a target异常。 - 空引用异常:Web API中未判断
existmovie是否为null,当通过movie.Trans_id找不到对应记录时,直接赋值引发NullReferenceException。
具体修复步骤
修正Web API路由
移除路由中的{movie}参数,PUT请求的实体数据应放在请求体中而非URL参数:[Route("Movies/Editstatus")]添加空值判断逻辑
在更新字段前先检查查询到的记录是否存在,避免空引用:using (var ctx = new MyEntity()) { var existmovie = ctx.Movie_transaction.Where(s => s.Trans_id == movie.Trans_id).FirstOrDefault(); if (existmovie != null) { existmovie.Transaction_status = movie.Transaction_status; ctx.SaveChanges(); } else { return NotFound(); // 返回404表示未找到目标记录 } }确认ExtJS模型主键配置
确保Movie.model.RentalStatusModel正确指定主键字段,保证sync时能传递有效ID:Ext.define('Movie.model.RentalStatusModel', { extend: 'Ext.data.Model', idProperty: 'Trans_id', // 必须配置主键字段 fields: [ 'Trans_id', 'refs', 'Transaction_status' // 其他字段... ] });检查请求数据有效性
在store1.sync()前打印待提交数据,确认Trans_id存在且正确:console.log(record1.getData()); // 验证Trans_id是否存在 store1.sync();简化HTTP方法标注
保留[HttpPut]即可,无需多余的AcceptVerbs:[HttpPut]
内容的提问来源于stack exchange,提问作者Bryan art

