You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sails.js控制器中实现类似ASP.NET GetEvents接口的JSON返回功能

Convert ASP.NET MVC EF JSON Action to Sails.js Controller

Got it, let's translate that ASP.NET MVC controller action into a working Sails.js controller method. Here's how you'd replicate the functionality step by step:

First, make sure you have your Event model set up in api/models/Event.js (this is the Sails equivalent of your EF Event entity, mapped to your database table). Then, open your controller file (e.g., api/controllers/EventController.js) and add this method:

module.exports = {
  getEvents: async function(req, res) {
    try {
      // Query events and sort by StartAt (adjust field name if your model uses camelCase)
      const events = await Event.find()
        .sort('startAt ASC'); // Use 'StartAt ASC' if your model keeps the C#-style camelCase field name

      // Return the sorted events as JSON
      return res.json(events);
    } catch (err) {
      // Handle database errors gracefully
      return res.serverError(err);
    }
  }
};

How this matches your original C# code:

  • Event.find() replaces dc.Events: Sails automatically registers your models globally once defined, so you don't need to manually create a database context like with EF's MyDatabaseEntities.
  • .sort('startAt ASC') is the equivalent of OrderBy(a => a.StartAt): Just make sure the field name matches whatever you've defined in your Sails model (most Sails apps use snake_case like start_at, but adjust to match your setup).
  • await gives you the sorted list directly, just like .ToList() does in EF.
  • res.json(events) sends the JSON response: Unlike ASP.NET MVC, Sails allows GET requests for JSON by default, so you don't need an equivalent to JsonRequestBehavior.AllowGet.
  • The try/catch block adds error handling, which is a helpful addition to make your app more resilient (your original C# code didn't include this, but it's good practice in Node.js/Sails).

内容的提问来源于stack exchange,提问作者Neeraj Bansal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:01:14