1

MVC4でAPIコントローラを介してJSONデータを返す正しい方法は何ですか? 変数型を関数として使う必要があると聞きましたが、使えないのでできません.Select(x => new { })

私が代わりに行うことは、dynamicそのように使用することです

[HttpGet]
public dynamic List() // Not List<Item>
{
    var items = _db.Items.OrderBy(x => x.ID).Select(x => new
    {
        ID = x.ID,
        Title = x.Title,
        Price = x.Price,
        Category = new {
            ID = x.Category.ID,
            Name = x.Category.Name
        }
    });

    return items;
}

これはこれを行う最良の方法ですか?私はMVC4を始めたばかりで、悪い習慣を早く身につけたくないので、私は尋ねています:)

4

2 に答える 2

3

組み込み関数Controller.Json( MSDN ) は、必要なことを行うことができます。つまり、コードがコントローラー クラス内にあると仮定します。

[HttpGet]
public dynamic List() // Not List<Item>
{
    var items = _db.Items.OrderBy(x => x.ID).Select(x => new
    {
        ID = x.ID,
        Title = x.Title,
        Price = x.Price,
        Category = new {
            ID = x.Category.ID,
            Name = x.Category.Name
        }
    });

    return Json(items, JsonRequestBehavior.AllowGet);
}

GET リクエストで使用する場合は、JsonRequestBehaviorフラグをパラメーターとして受け入れJsonRequestBehavior.AllowGet、そのパラメーターを指定するオーバーロードを使用する必要があります。

于 2012-09-04T10:38:51.570 に答える
1

を使用する必要はありません。簡単な方法は、匿名型dynamicを返すことです。object

[HttpGet] 
public object List() // Not List<Item> 
{ 
    var items = _db.Items.OrderBy(x => x.ID).Select(x => new 
    { 
        ID = x.ID, 
        Title = x.Title, 
        Price = x.Price, 
        Category = new { 
            ID = x.Category.ID, 
            Name = x.Category.Name 
        } 
    }); 

    return items; 
}

または、次を返しHttpResponseMessageます。

[HttpGet] 
public HttpResponseMessage List() // Not List<Item> 
{ 
    var items = _db.Items.OrderBy(x => x.ID).Select(x => new 
    { 
        ID = x.ID, 
        Title = x.Title, 
        Price = x.Price, 
        Category = new { 
            ID = x.Category.ID, 
            Name = x.Category.Name 
        } 
    }); 

    return Request.CreateResponse(HttpStatusCode.OK, items);
}
于 2012-09-04T10:45:22.100 に答える