Adding numbering for information from database - c#

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>}

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

Show the result of an int method in the Index View

I`ve made a simple method to count how many Albums do I have in a table, my only question is simple, I want to show the result of the Count method in the AlbumIndex view. Lets say I want to show a label: "Total" and the number besides it, how do I do this in the View?
This is the method(inside a class called Operations, separated from Controllers and Models):
public int AlbumCounter()
{
int x = db.Albums.Count();
return x;
}
This is the ActionResult Method in my AlbumsController(I don`t know what to do, I want to show the result in the Index View)
public ActionResult AlbumCounter()
{
return
}
and here is the Index View:
#model IEnumerable<AlexMusicStore.Models.Album>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Artist.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.AlbumName)
</th>
<th>
#Html.DisplayNameFor(model => model.DateCreated)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Artist.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.AlbumName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateCreated)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.AlbumID }) |
#Html.ActionLink("Details", "Details", new { id=item.AlbumID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.AlbumID })
</td>
</tr>
}
</table>

Passing list of data from controller to view

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).

Model Properties passing as nulls to Action

I am trying to pass an item with the type "EmployeeDocument" to my action but all of values are coming back as nulls and I am not sure why. I have tried passing the entire model as well as just pieces and they are all null and I am not sure why this is happening.
Here is what my view looks like:
<table id="results-table" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>
<u>#Html.DisplayName("Title")</u>
</th>
<th>
<u>#Html.DisplayName("Document Type")</u>
</th>
<th>
<u>#Html.DisplayName("Created By")</u>
</th>
<th>
<u>#Html.DisplayName("Created Date")</u>
</th>
<th style="width: 180px;"></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.DocumentType)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedBy)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedDate)
</td>
<td>View | #Html.ActionLink("Replace", "ReplaceEmployeeDocument", "Employee",new {title = item.Title, doctype = item.DocumentType, createdDate = item.CreatedDate,createdBy = item.CreatedBy, fullUrl = item.FullUrl}) | #Html.ActionLink("Delete", "DeleteEmployeeDocument",new {fileName = item.FullUrl, employeeNo = item.EmployeeNumber})</td>
</tr>
}
</tbody>
</table>
I am focusing on the replace action link in the table.
This is what my action looks like:
[HttpGet]
public ActionResult ReplaceEmployeeDocument(string title, string doctype, DateTime createdDate, string createdBy, string fullUrl)
{
var doc = new EmployeeDocument();
return PartialView(doc);
}
All of the parameters in the action are null. Is there a reason why these are like that?
You are trying to post back a collection of objects, in order for this to work you need to use a for loop and index the properties with hidden inputs as follows:
#using (Html.BeginForm("ReplaceEmployeeDocument", "Controller"))
{
#for(var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.HiddenFor(m => m[i].Title)
#Html.DisplayFor(m => m[i].Title)
</td>
<td>
#Html.HiddenFor(m => m[i].DocumentType)
#Html.DisplayFor(m => m[i].DocumentType)
</td>
<td>
#Html.HiddenFor(m => m[i].CreatedBy)
#Html.DisplayFor(m => m[i].CreatedBy)
</td>
<td>
#Html.HiddenFor(m => m[i].CreatedDate)
#Html.DisplayFor(m => m[i].CreatedDate)
</td>
<td>View | <input type="submit" value="Replace"/></td>
</tr>
}
}
You also need a corresponding post method that accepts the model being passed back:
[HttpPost]
public ActionResult ReplaceEmployeeDocument(EmployeeDocument model)
{
var doc = new EmployeeDocument();
return PartialView(doc);
}
You dont seem to be using any #Html.EditorFor which would generate input fields, and you dont have any form or javascript that would send your arguments in either GET or POST method. Therefore none of your fields are sent to the method in the controller. You should wrape the code inside the foreach in a
#Html.BeginForm() {}

Categories