默认值覆盖传递的值

时间:2011-09-20 22:35:17

标签: asp.net-mvc-3

我有一个接受多个值来过滤的操作。这些值是可选的。我设置了默认值。默认值将覆盖我传入的值。

如果我传入: minAge:40,maxAge:40。两个值都设置为0.

这是我控制器上的操作:

    [HttpGet]
    public ActionResult DataTableUpdate(string firstName = "", string lastName = "", int minAge = 0, int maxAge = 0, string currentState = "")
    {
        List<DataMember> data = DataMemberCache.GetMembers().FindAll(d => (d.FirstName.Contains(firstName)) && (d.LastName.Contains(lastName)) && (d.Age < minAge) && (d.Age > maxAge) && (d.CurrentState.Contains(currentState)));
        return PartialView("_DataTable", data);
    }

1 个答案:

答案 0 :(得分:1)

见这里:Optional parameters in the MVC framework are handled by using nullable-type arguments for controller action methods. 例如,如果方法可以将日期作为查询字符串的一部分,但是如果缺少查询字符串参数,则希望默认为今天的日期,您可以使用以下示例中的代码:

public ActionResult ShowArticles(DateTime? date)
{
    if(!date.HasValue)
    {
        date = DateTime.Now;
    }
    // ...
}

因此,您的代码必须更改为此代码:

[HttpGet]
public ActionResult DataTableUpdate(string firstName, string lastName, int? minAge, int? maxAge, string currentState)
{
    firstName = firstName ?? "";
    lastName = lastName ?? "";
    minAge = minAge ?? 0;
    maxAge = maxAge ?? 0;
    currentState = currentState ?? "";
    List<DataMember> data = DataMemberCache.GetMembers().FindAll(d => (d.FirstName.Contains(firstName)) && (d.LastName.Contains(lastName)) && (d.Age < minAge) && (d.Age > maxAge) && (d.CurrentState.Contains(currentState)));
    return PartialView("_DataTable", data);
}