ASP.NET MVC ActionLink如何保留“旧”的路由参数?

3

我有两个用于筛选的链接:

@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个回答

2
为什么不使用类似以下内容作为第二个链接:

为什么不使用这样的内容作为第二个链接:

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

如果提供了客户参数,它将在传递时传递该参数,但在为空时将传递 NULL。


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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接