1

ASP.netMVCプロジェクトで1つのモデルを作成しました。

public class ProductListingModels:ItemEntityDataContext
{
  public int ID { get; set; }
  public string Name { get; set; }
  public int DepartmentID { get; set; }
  public int BrandID { get; set; }
 }

そして私は1つのコントローラーを持っています:

public class ProductListingController : Controller
{
   // GET: /ProductListing/
   public JsonResult Index(string depID)
   {
   Context DataContext = new Context();
   JsonResult jr = new JsonResult();
   int dep = Convert.ToInt32(depID);
   var ien_item =   from i in DataContext.DataContext.Items
        join c in DataContext.DataContext.Categories on i.CategoryID equals c.ID
        join d in DataContext.DataContext.Departments on i.DepartmentID equals d.ID
        join brand in DataContext.DataContext.Brands on i.BrandID equals brand.ID
        orderby i.LastUpdated descending
        where i.DepartmentID == dep && i.Active > 0 && i.WebsiteShow > 0 && c.Active > 0 

                    select i;

     List<ProductListingModels> prom = new List<ProductListingModels>();
     //
     //Adding ien_item to the prom
     //
     jr.Data = prom;
         jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
         return jr;
   }
}
public class Context : ICEWeb.Models.ItemEntityDataContext
{

}

linq(ien_item)によってデータベースからクエリを実行した各データをProductListingModel(promオブジェクト)のオブジェクトに追加し、それをjsonとしてビューに返します。

誰かが私にいくつかのアイデアを教えてもらえますか?

本当にありがとう。

4

1 に答える 1

1

まず、モデルがデータコンテキストから継承されてはなりません。コンテキスト全体をビューに渡すことは、MVCの基本である関心の分離に重大な違反をします。次に、ビュータイプの要素を選択し、結果に対してToList()を呼び出す必要があります。

var model = (from i in DataContext.DataContext.Items
             join c in DataContext.DataContext.Categories on i.CategoryID equals c.ID
             join d in DataContext.DataContext.Departments on i.DepartmentID equals d.ID
             join brand in DataContext.DataContext.Brands on i.BrandID equals brand.ID
             orderby i.LastUpdated descending
             where i.DepartmentID == dep && i.Active > 0 && i.WebsiteShow > 0 && c.Active > 0 
             select new ProductListingModels
             {
                 ID = i.ID,
                 Name = i.Name,
                 ...
             }).ToList();

次に、独自の応答を作成するのではなく、Json()コンビニエンスメソッドを使用してデータを返すだけです。

 return Json( model, JsonRequestBehavior.AllowGet );
于 2012-04-19T01:28:50.713 に答える