Reputation: 423
I want to display an ID find in a datatable in a view. To do that, I do the following :
Create the function that will return the ID :
public int getClientID(string login)
{
var context = new MyEntity(new Uri("host/MyWCF.svc/"));
var userID = from persons in context.PERSON
where persons.LOGIN == login
select persons.USER_ID;
int uID = userID.First();
var cli = from client in context.CLIENT
where client.USER_ID == uID
select client.CLIENT_ID;
int cliID = cli.First();
return cliID;
}
And, in my view :
Client : @{ ((HomeController)(this.ViewContext.Controller)).getClientID(User.Identity.Name); }
Where HomeController is the name of my controller where the function is define. But doing this, i've got the following error :
Can only specify query options (orderby, where, take, skip) after last navigation
At line int uID = userID.First();
So, why do I have this error (since I'm using the good namespace in te view) and also, is it a good way to work ? Thanks !
Upvotes: 0
Views: 3734
Reputation: 11
You have to take first record inside your query itself like this,
public int getClientID(string login)
{
var context = new MyEntity(new Uri("host/MyWCF.svc/"));
var userID = (from persons in context.PERSON
where persons.LOGIN == login
select persons.USER_ID).FirstOrDefault(); //Take First ID here inside query
//So you can use userID directly in second query.
//But you have to check for null as well.
var cli = (from client in context.CLIENT
where client.USER_ID == userID
select client.CLIENT_ID).FirstOrDefault();
//int cliID = cli.First();
return cli ;
}
To call Controller method inside View easly you can do this as well,
In Controller's Action which loads your view (generally Its Index action)
Add this line to create new dynamic function inside ViewBag. ViewBag.GetClientID = new Func(getClientId);
And then add method in your controller
private int getClientId(string arg)
{
//Your stuff
}
You can call this method inside View like this,
@ViewBag.GetClientID("Your Input string")
Let me know whether it works?
Upvotes: 1
Reputation: 5318
@Html.Action("Home","getClientID", new {login=User.Identity.Name})
Upvotes: 1