Default value is overriding passed in values
I have an action that accepts multiple values to filter from. These values are optional. I set default values. The default values are overriding the values I pass in.
If I pass in: minAge:40, maxAge:40. Both values are set to 0.
This is the Action on my controller:
[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(开发者_JAVA百科lastName)) && (d.Age < minAge) && (d.Age > maxAge) && (d.CurrentState.Contains(currentState)));
return PartialView("_DataTable", data);
}
See here: Optional parameters in the MVC framework are handled by using nullable-type arguments for controller action methods. For example, if a method can take a date as part of the query string but you want to the default to be today's date if the query string parameter is missing, you can use code like that in the following example:
public ActionResult ShowArticles(DateTime? date)
{
if(!date.HasValue)
{
date = DateTime.Now;
}
// ...
}
So, your code must change to this one:
[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);
}
精彩评论