2012-07-05 20 views
2

我的兩個環節進行過濾:ASP.NET MVC ActionLink的保留「舊」路線參數

@Html.ActionLink("Customer 1", "Index", new { customer = 1 }) 
@Html.ActionLink("Project A", "Index", new { project = "A" }) 

我與過濾器:

public ViewResult Index(int? customer, int? project) { 
     var query = ... 

     if (customer != null) { 
      query = query.Where(o => o.CustomerID == customer); 
     } 

     if (project != null) { 
      query = query.Where(o => o.ProjectID == project); 
     } 
     return View(query.ToList()); 
} 

我現在可以在任何客戶或項目,但不能過濾在兩個同時!

如果我點擊客戶1,url = Object?customer=1

如果我點擊項目A,url = Object?project=a

我希望能夠首先單擊客戶1,然後項目A,並得到url = Object?customer=1&project=a

這是可能還是應該以另一種方式來做?

謝謝!

回答

1

正確的做法是將具有各種參數的模型返回到您的視圖。

型號

public class TestModel { 
    public int? Customer { get; set; } 
    public int? Project { get; set; } 
    public List<YourType> QueryResults { get; set; } 
} 

查看

@model Your.Namespace.TestModel 

... 

@Html.ActionLink("Project A", "Index", new { customer = Model.Customer, project = Model.Project }) 

控制器

public ViewResult Index(TestModel model) { 
    var query = ... 

    if (model.Customer != null) { 
     query = query.Where(o => o.CustomerID == model.Customer); 
    } 

    if (model.Project != null) { 
     query = query.Where(o => o.ProjectID == model.Project); 
    } 

    model.QueryResults = query.ToList(); 

    return View(model); 
} 
+0

+1這是正確的方式 – 2012-07-06 00:05:46

2

爲什麼不使用這樣的第二環節:

@Html.ActionLink("Project A", "Index", new { customer = ViewContext.RouteData["customer"], project = "A" }) 

這樣,當你擁有了它提供的客戶參數傳遞,而空時,它會通過NULL。