[英]Issue with returning object from a function in asp.net MVC
i am little confused about my code: 我对我的代码有点困惑:
Here is some function from my controller: 这是我的控制器提供的一些功能:
public void signIn(string userName, string userPass)
{
User user = new User();
user.getUser(userName , userPass);
if (user.userName != null)
{
Response.Redirect("/Home/Menu");
}
else
{
Response.Redirect("/Index/Index?Fail=" + "fail");
}
}
the " user.getUser" suppose to return a User object.. here is the code from my Model directory: “ user.getUser”应该返回一个User对象。这是我的Model目录中的代码:
public class User
{
public ObjectId _id { get; set; }
public string userName { get; set; }
public string userPass { get; set; }
public User getUser(string name , string pass)
{
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("testdb");
var coll = db.GetCollection<User>("user");
List<User> list = coll.Find(x => x.userName == name && x.userPass == pass).ToList<User>();
User uObj = new User();
uObj = list.FirstOrDefault();
return uObj;
}
}
when i am debugging the code i can see the uJob object contain values. 当我调试代码时,我可以看到uJob对象包含值。 but when the function end and i return to the controller i see that the user object contain only null values, and the condition - " if (user.userName != null)" is returning FALSE!.. instead of TRUE.. 但是当函数结束并且我返回到控制器时,我看到用户对象仅包含空值,并且条件-“ if(user.userName!= null)”返回FALSE!..而不是TRUE。
i would like to get some help. 我想得到一些帮助。 Thanks ! 谢谢 !
您必须分配它。
user = user.getUser(userName , userPass);
Either you assign the value returned by the getUser method in calling program like this 您可以像这样在调用程序中分配getUser方法返回的值
user = user.getUser(userName , userPass);
Or you change the code in Model like this 或者您像这样更改模型中的代码
public class User
{
public ObjectId _id { get; set; }
public string userName { get; set; }
public string userPass { get; set; }
public void getUser(string name , string pass)
{
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("testdb");
var coll = db.GetCollection<User>("user");
var user = coll.FirstOrDefault(x => x.userName == name && x.userPass == pass);
if(user != null)
{
this._id = user._id;
this.userName = user.userName;
this.userPass = user.userPass;
}
}
}
if you replace 如果您更换
if (user.userName != null)
with 与
if ( user.getUser(userName , userPass).userName != null)
wil works for you. 将为您工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.