ASP.NET MVC ActionLink保留“旧”路由参数

时间:2012-07-05 18:43:06

标签: asp.net-mvc

我的两个过滤器链接:

@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

这是可能的,还是应该以其他方式进行?

谢谢!

2 个答案:

答案 0 :(得分:2)

为什么不在第二个链接上使用这样的东西:

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

这样客户参数在提供时传入,但在空时传递NULL。

答案 1 :(得分: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);
}