Passing list of data from controller to view - c#

I'm trying to retrieve data in a specific order (to establish a ranking) with the below code:
public ActionResult ShowRanking(int id = 0)
{
Tournament tournament = db.Tournament.Find(id);
var parti = (from p in db.Participe
where p.IdTournament == tournament.IdTournament
//orderby p.ArchTotalScore descending
select p).OrderByDescending(x => x.ArchTotalScore);
//objlist = parti;
foreach (var part in parti)
{
tournament.Participe.Add(part);
//objlist.Add(part);
}
tournament.Participe.OrderByDescending(x => x.ArchTotalScore);
return View(tournament.Participe);
}
The data is retrieved but whenever I pass the list ofdata to my view, the order criterias I used are ignored and the records are shown as they have been inserted in the DB.
Here is my view as well:
#model ArcheryComp.Tournament
#{
ViewBag.Title = "Classement";
}
<h2>Classement</h2>
<table>
<tr>
<th>
Nom
</th>
<th>
Prenom
</th>
<th>
Division
</th>
<th>
Categorie
</th>
<th>
Score 1
</th>
<th>
Score 2
</th>
<th>
Total Score
</th>
</tr>
#foreach (var item in Model.Participe)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Archers.Nom)
</td>
<td>
#Html.DisplayFor(modelItem => item.Archers.Prenom)
</td>
<td>
#Html.DisplayFor(modelItem => item.Divisions.DivDescription)
</td>
<td>
#Html.DisplayFor(modelItem => item.Categorie)
</td>
<td>
#Html.DisplayFor(modelItem => item.ArchScore1)
</td>
<td>
#Html.DisplayFor(modelItem => item.ArchScore2)
</td>
<td>
#Html.DisplayFor(modelItem => item.ArchTotalScore)
</td>
<br />
</tr>
var tmp = item.IdTournament;
}
</table>
Do you have any idea what is wrong ? and could I correct this ?
Thanks in advance for your help.

You ordered the tournament.Participe, but you did not use the result. You must change it to something like this(if tournament.Participe is a Listofcourse):
tournament.Participe =
tournament.Participe.OrderByDescending(x => x.ArchTotalScore).ToList();
return View(tournament);
The model used in the view is ArcheryComp.Tournament therefore you must return View(tournament) not View(tournament.Participe).

Related

Change color in table row depending on cell value (minus/plus) in database

I have done a table of history transactions. In my transaction db I have a column named QuantityChange. Where values can be negative or positive.
I would like to set the row color to red, if its a minus value and green if positive (or zero).
What is the best solution to this?
<table class="table">
<thead>
<tr>
<th>
Date
</th>
<th>
Storage
</th>
<th>
Product
</th>
<th>
Quantity change
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class="#item.QuantityChange">
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stock.Storage.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stock.Product.Name)
</td>
<td>
#if (item.QuantityChange > 0)
{
#Html.DisplayFor(modelItem => item.QuantityChange, new {
style = "color:#00ff00" })
}
else
{
#Html.DisplayFor(modelItem => item.QuantityChange, new {
style = "color:#ff0000" })
}
</td>
</tr>
}
</tbody>
</table>
This might be a solution for you.
#foreach (var item in Model)
{
<tr style="color:#(item.QuantityChange >= 0 ? "#00ff00" : "#ff0000")">
<!-- insert other columns here -->
<td> <!-- this has been modified -->
#Html.DisplayFor(modelItem => item.QuantityChange)
</td>
</tr>
}
Try this
#{
String color;
}
And in your table add the styling to each element as required.
#foreach (var item in Model)
{
<tr>
#{
switch((item.QuantityChange)
{
case >0:
color:"#00ff00";
break;
default:
color:"color:#ff0000";
break;
}
<td style="color:#color">
#Html.DisplayFor(modelItem => item.QuantityChange)
</td>

How can I filter data in a Razor view with a dropdown

Hello I'm new to MVC and I'm trying to do a filtering for my index page, I want to be able to filter the graduation Status.
So when I go into the index I will see every status and I want to filter for example only the person with the graduated Status or the Pass/failed Status
Thank you in advance!
Index Page
Controller:
var graduates = db.Graduated_Students;
return View(graduates.ToList());
View:
<div class="content-body">
<div class="row">
<form action="#" method="post">
<div class="col-xs-12 col-sm-9 col-md-12">
<table class="table">
<tr>
<th>
#Resource.FirstName
</th>
<th>
#Resource.LastName
</th>
<th>
#Resource.CohortNumber
</th>
<th>
Placements
</th>
<th>
#Resource.GraduationStatus
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem =>
item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem =>
item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem =>
item.PartnerName)
</td>
<td>
#Html.DisplayFor(modelItem =>
item.GraduationStatus)
</td>
You could use linq in the View to filter the data
In the View
#foreach (var item in Model.Where(t=> t.GraduationStatus == <the graduation status selected in the dropdown> );
This approach Gets all the data from the database and then performs the filtering
That approach would work however a better approach would be to send the Selected GraduationStatus to the controller as a parameter and then perform the filtering directly on the db variable
In the Controller
public IActionResult GeStudents(GraduationStatus selectedGraduationStatus)
{
var graduates = db.Graduated_Students.Where(t=> t.GraduationStatus == selectedGraduationStatus);
return View(graduates.ToList());
}
This way you don't get all of the students from the database but only the ones which match the filter

Nested foreach loops within a table to return two lists of data

I have looked all over and found a number of solutions none of which have given the specific result that I want. I must be missing something obvious!
I am trying to get the list of a users current roles (stored in mysql db) and list show those in the same table as the list of users, below is all I can manage to get to work, a list of all roles that all users are in, not specific to each user. The User to UserRoles is a many-to-many relationship and as such the UseRoles_has_Users table was generated
Usertable
I have created a separate model for the admin index page
Model
namespace ComputerAidedDispatch.Models
{
public class AdminIndex : UserMetaData
{
public IEnumerable<User> AdminUsers { get; set; }
public IEnumerable<UserRoles_has_Users> AdminUserRoles { get; set; }
}
}
Controller
public ActionResult Index(string searchString)
{
var users = from u in db.Users
select u;
var userRoles = from r in db.UserRoles_has_Users
select r;
var adminIndex = new AdminIndex();
adminIndex.AdminUsers = users;
adminIndex.AdminUserRoles = userRoles;
if (!String.IsNullOrEmpty(searchString))
{
adminIndex.AdminUsers = adminIndex.AdminUsers.Where(s => s.username.Contains(searchString));
}
return View(adminIndex);
}
View
#model ComputerAidedDispatch.Models.AdminIndex
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
#using (Html.BeginForm())
{
<p>
User: #Html.TextBox("SearchString")
<input type="submit" value="Search!" class="btn btn-default" />
</p>
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.username)
</th>
<th>
#Html.DisplayNameFor(model => model.firstName)
</th>
<th>
#Html.DisplayNameFor(model => model.lastName)
</th>
<th>
#Html.DisplayNameFor(model => model.email)
</th>
<th>
#Html.DisplayNameFor(model => model.loginAttempts)
</th>
<th>
#Html.DisplayNameFor(model => model.accountBanned)
</th>
<th>
#Html.DisplayName("Roles")
</th>
<th>
#Html.DisplayName("Actions")
</th>
<th></th>
</tr>
#foreach (var item in Model.AdminUsers.ToArray())
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.username)
</td>
<td>
#Html.DisplayFor(modelItem => item.firstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.lastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
</td>
<td>
#Html.DisplayFor(modelItem => item.loginAttempts)
</td>
<td>
#Html.DisplayFor(modelItem => item.accountBanned)
</td>
<td>
#foreach(var role in Model.AdminUserRoles)
{
var userRole = role.UserRoles_roleName;
#Html.DisplayFor(modelItem => userRole)
}
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.userId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.userId })
</td>
</tr>
}
</table>
I feel like the .ToArray() in the line
Model.AdminUsers.ToArray()
Could be part of the problem, but that stopped me getting the exception
MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
I'm out of ideas so any help or suggestions greatly appreciated!
Thanks in advance!
Replace this section of your code in your controller:
var users = from u in db.Users
select u;
to be the following:
var users = db.Users.Include(u => u.UserRoles_has_Users.Select(s => s.Role)).ToList();
Then in your view you can do the following:
#foreach (var item in Model.AdminUsers.ToArray())
{
<tr>
//... other stuff
#foreach(var role in item.UserRoles_has_Users)
{
var userRole = role.UserRoles_roleName;
#Html.DisplayFor(modelItem => userRole)
}
//.... other stuff
}
The key here is that you want to loop over the roles in the item not in the role.
Note: the names of your properties may vary, if you include your Entity classes I can correct those.

How to add a where clause when returning a list in a view Mvc5

Is it possible to add a where clause in the view rather than the controller as I don't want to change the retrieval of information in the controller. I currently am retrieving a list of restaurants but want to only show restaurants where the logged in users email is the same as the restaurants email.
<div class="col-xs-12">
<table class="table table-condensed table-striped">
<tr>
<th>
#Html.DisplayNameFor(model => model.Rating)
</th>
<th>
#Html.DisplayNameFor(model => model.RestaurantName)
</th>
<th>
#Html.DisplayNameFor(model => model.County)
</th>
<th>
#Html.DisplayNameFor(model => model.RestaurantType)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
#Html.DisplayFor(modelItem => item.RestaurantName)
</td>
<td>
#Html.DisplayFor(modelItem => item.County)
</td>
<td>
#Html.DisplayFor(modelItem => item.RestaurantType)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.RestaurantID }) |
#Html.ActionLink("Details", "Details", new { id = item.RestaurantID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.RestaurantID })
</td>
</tr>
}
</table>
</div>
If you really don't want to change the logic for retrieving the list, you could use a ViewModel with a List property, returning the specified list using the Getter.
public List<Restaurant> MyRestaurants
{
get { return Restaurants.Where(x => x.RestaurantEmail == UserEmail); }
}

Adding numbering for information from database

I am using ASP>NET MVC and pulling information from the database and displaying it on a view page. It is working fine but is there any way I can add Index numbers at the start?
For example, at present the display is as follows:
Name Age Gender
Annie 24 Female
Aaron 17 Male
I am looking to make it:
Index Name Age Gender
1 Annie 24 Female
2 Aaron 17 Male
I could have pulled the IDs from the database but they are not necessarily going to be in proper incremental values. I tried and increment via a ViewBag but it doesn't work. Was expected considering the increment was occurring outside the list.. My code as follows at the controller and view.
//Controller
public ActionResult Index()
{
int count = 1;
ViewBag.Count = count++;
return View(db.Person.ToList());
}
//View
<table class="table">
<tr>
<th>
Index
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Age)
</th>
<th>
#Html.DisplayNameFor(model => model.Gender)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#ViewBag.Count
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
</tr>
}
</table>
Declare the counter in the view (no need for the ViewBag property) and increment it inside the loop
#{ int counter = 1; }
<table class="table">
<tr>
<th>Index</th>
<th>#Html.DisplayNameFor(model => model.Name)</th>
....
</tr>
#foreach (var item in Model) {
<tr>
<td>#counter</td>
<td>#Html.DisplayFor(modelItem => item.Name)</td>
....
</tr>
counter++;
}
</table>
Use "for loop" in razor, something like:
#for(var i = 10; i < 21; i++)
{<p>Line #i</p>}

Categories