代码之家  ›  专栏  ›  技术社区  ›  woggles

MVC排序与视图模型上的属性

  •  1
  • woggles  · 技术社区  · 8 年前

    假设我有一个呈现表的列表视图的视图模型。

    视图模型:

      public class SortModel
      {
         public List<Document> Documents {get;set;}
         public string SortParameter {get;set;}
         public string SortOrder {get;set;}
      }
    
      public class Document
      {
         public string Name {get;set;}
         public int Age {get;set;}
      }     
    

    查看:

       <th>@Html.DisplayNameFor(model => model.Documents[0].Name)</th>
       <th>@Html.DisplayNameFor(model => model.Documents[0].Age)</th>
    

    控制器:

    public ActionResult Index(SortModel model)
    {
       var docs = db.GetDocs();
       if(model.SortParameter == "Age" && model.SortOrder == "desc")
       {
          docs.OrderByDescending(x => x.Age);
       }  
       return View(model); 
    }
    

    如何呈现视图,使表标题可单击,并在发布前更新模型?我想避免使用ViewBag。

    我猜我需要使用ActionLink,但我不确定在发布之前如何更新模型。

    类似于:

    <th>@Html.ActionLink("Index", "Home", "Name", new { Model.SortParameter = "Name", Model.SortOrder = "Desc"})
    

    1 回复  |  直到 8 年前
        1
  •  2
  •   user3559349 user3559349    8 年前

    将表格标题更改为

    <th>@Html.ActionLink("Name", "Index", "Home", new { SortParameter = "Name", SortOrder = Model.SortOrder }, null)</th>
    <th>@Html.ActionLink("Name", "Index", "Home", new { SortParameter = "Age", SortOrder = Model.SortOrder }, null)</th>
    

    然后修改控制器方法以切换 SortOrder

    public ActionResult Index(SortModel model)
    {
       var docs = db.GetDocs();
       if(model.SortParameter == "Age" && model.SortOrder == "desc")
       {
          docs.OrderByDescending(x => x.Age);
          model.SortOrder == "acs"
       }  
       return View(model); 
    }
    

    请注意,如果您有 bool IsAscending 而不是您的 string SortOrder

    但是,您只有一个“SortOrder”属性,因此如果当前视图显示按排序的文档 Name 按升序,用户单击 Age ,则文档将按 年龄 按升序排列。如果用户单击 名称 ,文档将按 名称 按降序排列。您尚未说明所需行为的原因,但可以添加多个“SortOrder”属性,例如

    public bool IsNameAscending { get; set; }
    public bool IsAgeAscending { get; set; }
    

    来处理这个问题,并且允许您使用 .ThenBy() 例如,在查询中

    docs.OrderBy(x => x.Age).ThenBy(x=> x.Name);
    

    您可能还希望呈现视觉指示器(例如向上或向下箭头),以向用户指示当前排序顺序。