Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用搜索栏,我只想显示属于当前用户的项目,那么我的代码怎么了?_C#_Asp.net_Asp.net Mvc - Fatal编程技术网

C# 使用搜索栏,我只想显示属于当前用户的项目,那么我的代码怎么了?

C# 使用搜索栏,我只想显示属于当前用户的项目,那么我的代码怎么了?,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我想查看属于当前用户的项目。在Idex中,我使用GET方法显示属于当前用户的产品,但当我尝试搜索某个项目时,它会显示所有项目,甚至是不属于当前用户的项目。那么错误在哪里呢 public ActionResult Index() { string currentUserId = User.Identity.GetUserId(); var userProducts = db.Products.Where(p => p.UserI

我想查看属于当前用户的项目。在Idex中,我使用GET方法显示属于当前用户的产品,但当我尝试搜索某个项目时,它会显示所有项目,甚至是不属于当前用户的项目。那么错误在哪里呢

public ActionResult Index()
        {
            string currentUserId = User.Identity.GetUserId();
            var userProducts = db.Products.Where(p => p.UserId == currentUserId).ToList();
            return View(userProducts);

        }
    
    public ActionResult Index(string searchTxt)
                {
                    string currentUserId = User.Identity.GetUserId();
                    var userProducts = db.Products.Where(p => p.UserId == currentUserId);
                    if (searchTxt != null)
                    {
                        userProducts = db.Products.Where(x => x.Denumire.Contains(searchTxt));
                    }
                    return View(userProducts.ToList());
                }

您需要组合两个linq语句:

string currentUserId = User.Identity.GetUserId();
var userProducts = db.Products.Where(p => p.UserId == currentUserId);
if (searchTxt != null && userProducts.Any())
{
    // use the previous filtered products here
    userProducts = userProducts.Where(x => x.Denumire.Contains(searchTxt));
}
return View(userProducts.ToList());

您需要组合两个linq语句:

string currentUserId = User.Identity.GetUserId();
var userProducts = db.Products.Where(p => p.UserId == currentUserId);
if (searchTxt != null && userProducts.Any())
{
    // use the previous filtered products here
    userProducts = userProducts.Where(x => x.Denumire.Contains(searchTxt));
}
return View(userProducts.ToList());
在第二个查询中不使用userProducts,而是在整个Products表中搜索searchText。这就是为什么您得到的结果甚至不是来自用户的。如果在第二次查询中不使用userProducts,您可以在整个Products表中搜索searchText。这就是为什么你得到的结果甚至不是来自用户