簡體   English   中英

使用MVC4返回值的正確方法

[英]Correct way to return values using MVC4

在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而且我不想早點養成壞習慣:)

內置函數Controller.JsonMSDN )可以做你想要的,即假設你的代碼駐留在控制器類中:

[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參數指定JsonRequestBehavior.AllowGet

您不需要使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM