In my View() i have many checkboxes with attr name="types". In my ActionResult I have a List types like parameter, and I do foreach loop to search in List, each type ID and add a Where() filter in my LINQ expression. If I select many types, the return is only one result and dont all what i chose. Look:
[HttpPost]
public ActionResult Index(List<int> types) {
var variable = from s in MyViewModel select s;
foreach(var type in types) {
variable = variable.Where(x => x.TypesId == type);
}
return View(MyViewModel);
}
Is there another way to do this?
Thank you!!
variable = variable.Where(x => types.Contains(x.TypesId));
这应该为您提供所有值,如果只需要一个,请在末尾添加.FirstOrDefault()
There are few problems in your code, no matter what other part of code do your return statement always returns all MyViewModel
collection.
Other problem is your code overwrite variable
inside the loop.
I think, this is what you need.
return View(MyViewModel.Select(s=> types.Any(t=>t.type == s.TypesId));
make attr name from name="types" to name="types[]"
and it will post array of selected values
The variable
is being reset each foreach
iteration. Create a List
and add to it in foreach
block.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.