【问题标题】:Sencha ExtJS 5 with ASP.NET MVC - Save Model via ProxySencha ExtJS 5 与 ASP.NET MVC - 通过代理保存模型
【发布时间】:2023-04-05 15:41:01
【问题描述】:

我刚刚开始使用带有 ASP.NET Web API 的 Sencha ExtJS 5。

其中一个基本示例是创建模型并将数据发布到“代理”。

http://docs.sencha.com/extjs/5.0/apidocs/#!/api/Ext.data.Model-cfg-proxy

我的 ExtJS 代理正在发布到 ASP.NET Web API,它在 Id 列中需要 NULL 值,以便作为新记录插入到 db。

问题在于 ExtJS 的“create”函数会自动为模型 id 列生成一个字符串 id(例如 SessionModel-1)。

我附上了保存请求负载的屏幕截图。

 Ext.define("SessionModel", {
        extend: "Ext.data.Model",
        fields: [
            { name: 'id', type: 'int' },
            { name: 'title', type: 'string' },
            { name: 'approved', type: 'bool' , defaultValue : false }
        ],

        proxy: {
            type: 'rest',
            url: '/api/Session'

        }

    });

    var mySession1 = Ext.create("SessionModel", {
        title: 'C++',
        approved: true,
    });


  mySession1.save();

Session.cs - 模型已定义:

namespace WebApplication1.Models
{
    public class Session
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Approved { get; set; }
    }
}

SessionController.cs - 控制器 POST :

 // POST api/Session
[ResponseType(typeof(Session))]
public IHttpActionResult PostSession(Session session)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Sessions.Add(session);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = session.Id }, session);
}

如何阻止 ExtJS 自动生成 id 或使用“保存”的正确方法是什么?

【问题讨论】:

  • 在 ModelState 检查之前设置 session.Id = 0...

标签: asp.net asp.net-mvc extjs extjs4 extjs5


【解决方案1】:

是的,extjs 正在填充idProperty,因为他们需要它来处理内部事务。如果您想在客户端进入服务器之前设置您的 id 属性,您应该创建自定义代理类并覆盖buildRequest。在那里您可以检查所需的操作是否为create 并相应地设置idProperty

buildRequest: function(operation) {
    var request = this.callParent(arguments);

    if (request.getAction() === 'create') {
        request.getRecords().forEach(function(record) {
            record.set('carId', ''); //assing desired value 
        });
    }

    return request;
}

这是来自 Skirtle 的一个不错的 post about custom proxies

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多