Reputation: 685
I use Linq to SQL as data access layer in ASP.NET MVC application. So the query result is a strong typed object. How can I dynamiclly specify which field to show in the page.
For example, the query result has the following fields: FirstName LastName Address Tel
My question is if one user wanna show the Lastname and the Firstname. 2nd user wanna show the Address and Firstname, 3rd etc... Different user has different requirements. So how can I query the database/filter the result based on user's specific requirement(on demand)?
To be more specific, the query result is a set of person information.
public class Person
{
public string FirstName {get;set;}
public string LastName {get;set;}
public string Tel {get;set;}
public string Tel {get;set;}
}
Upvotes: 0
Views: 2862
Reputation:
1) User indicates in the UI what results the user wishes to see
2) The Controller interprets this and stores this for later
3) The Controller goes to the DAL and gets the data from the DAL
4) The Controller then modifies the return result somehow according to #2
5) The Controller then passes the modified data to the UI
6) The UI renders the data
I think your disconnect starts at 4 and may extend as far as 6.
The fact is that there are literally thousands of ways to do this. Here's one way to do it in amazingly C#-like pseudocode.
First, I'd create a view model that contains information on what I want to display to the user.
Original Linq to Sql (abbreviated):
public class Person
{
public string FirstName {get;set;}
public string LastName {get;set;}
public string Tel {get;set;}
}
My view model:
public partial class PeopleView
{
public bool ShowFirstName {get;set;}
public bool ShowLastName {get;set;}
public bool ShowTel {get;set;}
public IEnumerable<Person> People {get;set;}
}
The controller method that preps the model:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PersonDetails(bool showFirstName,
bool showLastName, bool showTel)
{
var viewData = new PeopleView()
{
ShowFirstName = showFirstname,
ShowLastName = showLastName,
ShowTel = showTel,
People = Dal.GetPeople()
};
return View(viewData);
}
And here's the View:
<% foreach(var item in ViewData.Model.People){ %>
<% if(ViewData.Model.ShowFirstName) {%>
<%= item.FirstName %><br/>
<% } %>
<% if(ViewData.Model.ShowLastName) {%>
<%= item.LasttName %><br/>
<% } %>
<% if(ViewData.Model.ShowTel) {%>
<%= item.Tel %><br/>
<% } %>
<% } %>
Upvotes: 1
Reputation: 59
Use an if statement based upon user input. I am assuming you stored the User's preference somewhere, in which case the following code would do the trick:
if (showAddress)
{
var results = from u in Users
select new
{
FirstName = u.FirstName;
LastName = u.LastName;
Address= u.Address;
}
// Code to display results goes here
}
else
{
var results = from u in Users
select new
{
FirstName = u.FirstName;
LastName = u.LastName;
}
// Code to display results goes here
}
Upvotes: 0