[英]LINQ - Wildcard on an int column in ASP.NET Core
I have a table that returns records from the database.我有一个从数据库返回记录的表。 The users have various dropdowns and input boxes where they can search specific results within columns.
用户有各种下拉菜单和输入框,他们可以在其中搜索列中的特定结果。 I have an input box that searches a column that takes an int and null values.
我有一个输入框,用于搜索采用 int 和 null 值的列。 If the user does not specify anything inside of the input box, I want to return all applicable records from that column.
如果用户没有在输入框中指定任何内容,我想从该列返回所有适用的记录。
Either the value of the classroom size input box is an integer, or it is set as a wildcard if the user does not specify.教室大小输入框的值要么是integer,要么是用户不指定的情况下设置为通配符。 This is why I run into a cast issue.
这就是我遇到演员阵容问题的原因。
The way I have it set it up now returns a 400 status if I do not specify an integer in the input box.如果我没有在输入框中指定 integer,那么我设置它的方式现在会返回 400 状态。 Please let me know how I can accomplish my goal, thank you for your time!
请让我知道如何实现我的目标,谢谢您的时间!
View:看法:
@model IEnumerable<MyApp.Models.tblClassrooms>
<div>
<form method="get" role="form" asp-controller="Classroom" asp-action="Index">
<label>Class Size</label>
<input type="search" value="@ViewData["sizeSearch"]" name="sizeSearch" />
<input asp-controller="Classroom" asp-action="Search" value="Search" type="submit" />
</form>
</div>
Controller: Controller:
[HttpGet("[action]")]
public async Task<IActionResult> Search(string sizeSearch)
{
ViewData["sizeSearch"] = sizeSearch;
var query = from x in _db.tblClassrooms
.Where(x => x.ID == 10)
select x;
if (string.IsNullOrEmpty(sizeSearch))
{
//set a variable equal to a 'wildcard'
//this is where I run into a cast issue
}
//adding to the query above, search by that table, where the ID is 10,
//furthermore, search by either the classroom size or the wildcard
query = query.Where(x =>
x.ClassSize.Equals(sizeSearch));
return View("Index", await query.AsNoTracking().ToListAsync());
}
Note: I am using ID = 10 for testing purposes.注意:我使用 ID = 10 进行测试。 Please keep in mind that I have other values that I am also searching by.
请记住,我还有其他值,我也在搜索。
If I understand your usage of the word 'wildcard' correctly, you could just omit the second where clause:如果我正确理解您对“通配符”一词的使用,您可以省略第二个 where 子句:
if (!string.IsNullOrEmpty(sizeSearch))
{
query = query.Where(x => x.ClassSize.Equals(sizeSearch));
}
This way, if nothing is passed into sizeSearch
, you will not be filtering your query by it.这样,如果没有任何内容传递给
sizeSearch
,您将不会通过它过滤您的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.