如何发送数据控制器到视图

本文关键字:视图 控制器 数据 何发送 | 更新日期: 2023-09-27 17:49:35

public ActionResult Detay(int? categoryId)
{
    var categories = categoryService.CategoriesToList();
     if (categoryId == null)
     {
        var products = productService.Products().ToList();  
        return RedirectToAction("Index");
     }
     else
     {
        var products = productService
                      .CategoryProducts((int) categoryId, 50)
                      .ToList();
        var result = products.Where(a => a.CategoryId == categoryId);
        return View(result);
     }
}

我有产品控制器,这是我的方法发送产品按类别查看。

我想在View中检查categoryId

这样的;

@if(categoryId==1){//do this.}

但是我不能到达categoryId我怎么能发送数据并从视图获取数据?

如何发送数据控制器到视图

根据你的控制器代码,你的视图接收IEnumerable<Product>作为模型,而不是Product本身。或者创建一个新的视图模型并使用它:

public class ProductsViewModel
{
   public int CategoryId {get;set;}
   public IEnumerable<Product> Products {get;set;}
}

和在你看来:

@model ProductsViewModel
@if(Model.CategoryId==1)..

或者在您的视图中使用@Model.First().CategoryId

视图模型:

public class ProductsViewModel
{  
   public int CategoryId{get;set;}
   public IEnumerable<Product> Products {get;set;}
}

控制器:

public ActionResult Detay(int? categoryId)
{
  var productVM= new ProductsViewModel();
  var products = productService
                      .CategoryProducts((int) categoryId, 50)
                      .ToList();
   productVM.Products = products.Where(a => a.CategoryId == categoryId);
   productVM.CategoryId=1 // ex. your value
   return View("Detay", productVM);
}

视图:

@model ProductsViewModel
@if(Model.CategoryId==1).. // then you can use like this.

注意:你可以不使用viewmodel。在这种情况下,向模型类声明属性。为该属性赋值并将该模型传递给视图。

您可以通过ViewBag发送类别id,

in Controller's Action:

ViewBag.CategoryId = categoryId;
在视图:

@if (ViewBag.CategoryId == 1)
{
}