Asp.net mvc 在MVC中显示当前用户数据

Asp.net mvc 在MVC中显示当前用户数据,asp.net-mvc,asp.net-mvc-3,Asp.net Mvc,Asp.net Mvc 3,在MVC中,我想对用户进行身份验证,他们在登录时不能看到其他用户数据。用户必须只能对自己的数据进行CRUD。我创建了两个模型: public class User { public int id { get; set; } public string Username { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } publi

在MVC中,我想对用户进行身份验证,他们在登录时不能看到其他用户数据。用户必须只能对自己的数据进行CRUD。我创建了两个模型:

public class User
{
    public int id { get; set; }
    public string Username { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }

    public List<Product> Products { get; set; }
}


public class Product
{
    public int productId { get; set; }
    public string productName { get; set; }
    public double productPrice { get; set; }

    public User Users { get; set; }
}
公共类用户
{
公共int id{get;set;}
公共字符串用户名{get;set;}
公共字符串名{get;set;}
公共字符串Lastname{get;set;}
公共列表产品{get;set;}
}
公共类产品
{
public int productId{get;set;}
公共字符串productName{get;set;}
公共双产品价格{get;set;}
公共用户用户{get;set;}
}

我还有product controller,我想在其中验证来自CRUD其他用户数据的用户。

您可以使代码仅对登录用户可用的产品执行CRUD操作。 根据您的需求使用以下场景

public class User
{
    public int id { get; set; }
    public string Username { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }

    public List<Product> Products { 
        get{ 
            //get all products from database/storage for this user. for ex: I have called a method to get products
            //you can filter products related to this user by sending this user id to database or using code like below
            //Writing this code/logic in controller would be preferable

            return GetAllProducts().Where(p => p.Users.id == this.id).ToList();
        }
        set; 
    }
}
公共类用户
{
公共int id{get;set;}
公共字符串用户名{get;set;}
公共字符串名{get;set;}
公共字符串Lastname{get;set;}
公开列表产品{
获取{
//从数据库/存储中获取此用户的所有产品。例如:我调用了一个方法来获取产品
//您可以通过将此用户id发送到数据库或使用如下代码筛选与此用户相关的产品
//最好在控制器中编写此代码/逻辑
返回GetAllProducts().Where(p=>p.Users.id==this.id).ToList();
}
设置
}
}

同意拉杰什的意见,我建议您使用当前用户的数据,并过滤您显示的拉杰什。当前用户的数据可能包括当前登录用户的Id。如果您使用cookie来保持用户会话,您可以从controller或filter属性中的cookie中检索他的Id:
HttpContext.Current.Request.cookies[“auth_cookie”]

此站点用于回答特定问题,最好是在您尝试过之后。谷歌asp mvc教程,如果你不知道从哪里开始。你应该找到一些信息。