I have a bootstrap datatable in my view in a MVC application. I use the sorting functionality provided to sort it by a column called CreatedOn and load it on the screen.
<div class="container">
<div class="no-more-tables">
<table id="tblTemplate" class="table table-advance dataTable">
<thead>
<tr>
<th style="display:none">
ID
</th>
<th style="width:14%">
Type
</th>
<th style="width:25.5%;">
Subject
</th>
<th style="width:15%;">
Created By
</th>
<th style="width:15%;">
Created on
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.lstBoxes)
{
<tr>
<td class="text-left" style="display:none">#item.Id</td>
<td class="text-left">#item.Type</td>
<td class="text-left">#item.Subject</td>
<td class="text-left">#item.CreatedBy</td>
<td class="text-left">#item.CreatedOn</td>
</tr>
}
</tbody>
</table>
</div>
</div>
The sorting functionality script on load:
function initialSortCommon(tblName,colNo) {
$("#tblTemplate").dataTable(
{
"bDestroy": true
}
).fnDestroy();
$(document).ready(function () {
$("#tblTemplate").dataTable({
"bDestroy": true,
"aaSorting": [[4, 'desc']],
"oLanguage":
{
"sSearch": "Search all columns:",
},
});
});
}
The issue is the sorting behaves differently when fed a list using SQL Statements and when using Linq
var lstBoxes = new List<Record>();
var con = new SqlConnection(cs);
con.Open();
var command = new SqlCommand("SELECT ID,Type,Subject,CreatedBy,CreatedOn FROM Box", con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
lstBoxes.Add(new Record { Type = Convert.ToString(reader["Type"]), Id = Convert.ToString(reader["ID"]), Subject = Convert.ToString(reader["Subject"]), CreatedBy = Convert.ToString(reader["CreatedBy"]), CreatedOn = Convert.ToString(reader["CreatedOn"]) });
}
con.Close();
return lstBoxes;
Using Linq:
var lstBoxes = db.Boxs.Select(s => new Record
{ Type = s.Type, Id = s.ID.ToString(), Subject = s.Subject, CreatedBy = s.CreatedBy, CreatedOn = s.CreatedOn.ToString() }).ToList();
return lstEvents;
Even though both tables return same data, the sorting on the Created on works perfectly with SQL Server but not with LINQ. Is this a known issue?
EDIT : Removed the descending by in LINQ to make both code consistent.
EDIT 2 : I checked the results of both lists. There is a difference in the way the date is being retrieved.
For example : In SQL, the field Convert.ToString(reader["CreatedOn"]) is being retrieved as 11/7/2017 9:51:26 AM where as in LINQ CreatedOn = s.CreatedOn.ToString() gives Nov 7 2017 9:51 AM. This might be the cause of the issue. Is there a way the LINQ string be formatted similar to SQL result string?
Related
I have a table like this:
<table border="0" cellpadding="0" cellspacing="0" id="table2">
<tr>
<th>Name
</th>
<th>Age
</th>
</tr>
<tr>
<td>Mario
</td>
<th>Age: 78
</td>
</tr>
<tr>
<td>Jane
</td>
<td>Age: 67
</td>
</tr>
<tr>
<td>James
</td>
<th>Age: 92
</td>
</tr>
</table>
I want to get the last td from all rows using Html Agility Pack.
Here is my C# code so far:
await page.GoToAsync(NumOfSaleItems, new NavigationOptions
{
WaitUntil = new WaitUntilNavigation[] { WaitUntilNavigation.DOMContentLoaded }
});
var html4 = page.GetContentAsync().GetAwaiter().GetResult();
var htmlDoc4 = new HtmlDocument();
htmlDoc4.LoadHtml(html4);
var SelectTable = htmlDoc4.DocumentNode.SelectNodes("/html/body/div[2]/div/div/div/table[2]/tbody/tr/td[1]/div[3]/div[2]/div/table[2]/tbody/tr/td[4]");
if (SelectTable.Count == 0)
{
continue;
}
else
{
foreach (HtmlNode row in SelectTable)//
{
string value = row.InnerText;
value = value.ToString();
var firstSpaceIndex = value.IndexOf(" ");
var firstString = value.Substring(0, firstSpaceIndex);
LastSellingDates.Add(firstString);
}
}
How can I get only the last column of the table?
I think the XPath you want is: //table[#id='table2']//tr/td[last()].
//table[#id='table2'] finds the table by ID anywhere in the document. This is preferable to a long brittle path from the root, since a table ID is less likely to change than the rest of the HTML structure.
//tr gets the descendent rows in the table. I'm using two slashes in case there might be an intervening <tbody> element in the actual HTML.
/td[last()] gets the last <td> in each row.
From there you just need to select the InnerText of each <td>.
var tds = htmlDoc.DocumentNode.SelectNodes("//table[#id='table2']//tr/td[last()]");
var values = tds?.Select(td => td.InnerText).ToList() ?? new List<string>();
Working demo here: https://dotnetfiddle.net/7I8yk1
Hi this probably is an easy question but i cant find information about how to solve it i have a table with a field named Email and the values are of type string but the problem is that mvc or the browser automatically changes that string email into Hyperlink as shown in the following picture
when i inspect the element it is an hyperlink:
lacubana#la.com
what can i do to only display the emails as string? i don't want that information to be in hyperlink format. thanks very much
Edited: here is my code of the view
<table class="table table-bordered table-striped">
<tr>
<th>Email</th>
<th>Contraseña</th>
<th>NickName</th>
<th>TipoUsuario</th>
<th>Acciones</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Email)</td>
<td>#Html.DisplayFor(modelItem => item.Contraseña)</td>
<td>#Html.DisplayFor(modelItem => item.NickName)</td>
#if (item.TipoUsuario == 1)
{
<td>Administrador</td>
}
else
{
<td>Vendedor</td>
}
<td>
#Html.ActionLink("Editar", "EditarUsuario", new { id = item.IdUser }) |
#Html.ActionLink("Eliminar", "EliminarUsuario", new { id = item.IdUser })
</td>
</tr>
}
</table>
and here is the code of my controller:
IList<Usuario> UsuarioList = new List<Usuario>();
var query = from usu in database.ReportingUsersT
where usu.Activo == 1
select usu;
var listdata = query.ToList();
foreach (var Usuariodata in listdata)
{
UsuarioList.Add(new Usuario()
{
IdUser = Usuariodata.IdUser,
Email = Usuariodata.Email,
Contraseña = Usuariodata.Contraseña,
NickName = Usuariodata.NickName,
TipoUsuario = Usuariodata.TipoUsuario
});
}
return View(UsuarioList);
#Html.DisplayFor(...) is determining that the text is an email and is wrapping it in a link. You can simply use
<td>#item.Email</td>
to display it as text
I am working on an ecommerce site where I am stuck on the cart management. Basically before login, products are kept in a session and I am trying to update the product quantity stored in the session using Ajax. I mean whenever I write in the 'Quantity To Change', the changed value should be reflected in the 'Quantity' column.
Note: I've shortened the post and figured out why it wasn't firing while debugging. Actually I was unable to get the id of the associated product. Now it passes the id. That's it. Now I've another issue - The TextBox are being created dynamically with a for loop. I used developer tools to figure out how the TextBoxes are generated dynamically and it is something like this:
For Product 1: cartDetails_0__Quantity
For Product 2: cartDetails_1__Quantity
I am wondering how to grab the quantity or values from the dynamically generated TextBoxes. If I put the generated id from HTML directly to Ajax, then it updates the quantity. Otherwise it doesn't. I've tried to use a loop in Ajax but I think, I am getting it wrong. Please see the View.
The view:
<table border="1" width="100%" cellpadding="4">
<thead>
<tr>
<th style="text-align:center;">Name</th>
<th style="text-align:center;">Price</th>
<th style="text-align:center;">Quantity</th>
<th style="text-align:center;">Quantity To Change</th>
</tr>
</thead>
<tbody>
#if (ViewBag.CartDetails != null)
{
for (int i = 0; i < cartDetails.Count(); i++)
{
<tr>
<td style="text-align: center; display:none;">#Html.DisplayFor(model => cartDetails[i].ProductId)</td>
<td id="ID" style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].ProductName)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Price)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Quantity, new { #class = "quantityUpdate" })</td>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Quantity, new { #class = "quantity", data_id = cartDetails[i].ProductId } )</td>
</tr>
}
}
</tbody>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var url = '#Url.Action("UpdateCart")';
$(".quantityUpdate").change(function () {
var id = $(this).data('id');
var i = 0;
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, Quantity: $("#cartDetails_"+i+"__Quantity").val() }, function (response) {
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
alert(id);
alert($("#cartDetails_"+i+"__Quantity").val());
});
Here is an image sample that I am trying:
$('.quantity').change(function(){
$('.quantityUpdate').val($('.quantity').val());
// put code here
});
Instant Change
$('.quantity').keyup(function(){
$('.quantityUpdate').val($('.quantity').val());
// put code here
});
If the idea is to call ajax when you change the value in .quality textbox then this is how you should do:
$('.quantity').change(function(){
//your ajax call
});
I currently have a for-loop in my .cshtml file which iterates through items inside a ViewBag. I want to sort these objects based on a DateTime property called orderDate in the Order.cs file. The for loop in the .cshtml file looks like the following:
<table id="order-history-table" class="table table-hover">
<thead>
<tr>
<th>
Order Number
</th>
<th>
Order Date
</th>
<th>
Order Total
</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.list)
{
<tr>
<td>
<a class="orderNumber" data-toggle="modal" data-target="#modal-container" href="#Url.Action("orderDetails", "Orders", new { orderNumber = item.order.OrderNumber })">#item.order.OrderNumber</a>
<br />
#Html.ActionLink("Re-Order", "ReOrder", new { orderNumber = #item.order.OrderNumber }, new { onclick = "return confirm('Are you sure you wish to re-order?');" })
</td>
<td>#item.order.OrderDate.ToString("dd/MM/yyyy")</td>
<td style="text-align: center">$#(Math.Round(item.order.OrderTotal, 2))</td>
</tr>
}
</tbody>
I want this table to be sorted so that the most recent orders are shown at the top of the table. Since the data is being pulled from a database, and the tables values are generated dynamically, where do I perform this sorting? is it done through jQuery? How do I do this?
Thank you in advance
You can use LINQ OrderBy to do that.
So in your action method where you set the ViewBag.list, You can use OrderByDescending method on the collection.
var yourOrderList=new List<Order>();
// to do : Load Order items to yourOrderList
yourOrderList=yourOrderList.OrderByDescending(f=>f.OrderDate).ToList();
ViewBAg.list=yourOrderList;
I also recommend using a view model to pass data from your action method to view.
var yourOrderList=new List<Order>();
// to do : Add orders to yourOrderList
yourOrderList=yourOrderList.OrderByDescending(f=>f.OrderDate).ToList();
return View(yourOrderList);
And in your view
#model List<Order>
<h3>Orders</h3>
#foreach(var o in Model)
{
<p>#o.OrderDate.ToString()</p>
}
Since your view is strongly typed, you can do the same ordering in your razor view also as needed.
#model List<Order>
<h3>Orders</h3>
#foreach(var o in Model.OrderByDescending(g=>g.OrderDate))
{
<p>#o.OrderDate.ToString()</p>
}
im using the sortable jquery plugin, because i want that the user can choice the order of the images are showing in my view.
For this i have a Get Controller which sends the data to my PartialView.
How can i make the now the Post Controller to update my table in my database?
Note: In this moment the controller don´t receive any data. i haven´t figured out what is wrong
Someone can help me with this?
Thanks in advance:
Here is my code:
In My PartialView:
#(Html.BeginForm("UpdateOrder", "Admin", FormMethod.Post)){
<div id="Order">
<ul id="sortable">
#foreach (var p in ViewBag.Images)
{
<li id="#Html.AttributeEncode(p.FileName)">
<img src="~/Files/#p.FileName"/>
</li>
}
</ul>
</div>
}
Controller:
if (ModelState.IsValid)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("Update Image Set MyFileName=??? Order By ASC");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add(??????????).Value = ;
cmd.ExecuteNonQuery();
cn.Close();
}
}
return View();
Are you looking for something like this?
SqlCommand comm = new SqlCommand("UPDATE Customers SET Name=#name WHERE ID=#id", con;
comm.Parameters.AddWithValue("#name", "John");
comm.Parameters.AddWithValue("#id", id);
For passing data from view to controller take a look at the following links: ASP.NET MVC 3 Razor: Passing Data from View to Controller
ASP.Net MVC Passing multiple parameters to a view
I have created a backend for a website, where i e.g. can add, edit, delete events. So the snippet in the view for the events looks like this:
<div id="tabs-2" class="ui-widget-content">
<h2>
Events</h2>
<p>
#Html.ActionLink("Create new Event", "EventCreate")
</p>
<table id="tableEvent">
<tr>
<th>
Event
</th>
<th>
Date
</th>
<th>
Day of the Week
</th>
<th>
</th>
</tr>
#foreach (var e in ViewBag.Events)
{
<tr id="#e.EventID">
<td>
<h4>#e.EventName</h4>
</td>
<td>
<h4>#string.Format("{0:d}", e.Datum)</h4>
</td>
<td>
<h4>#e.Tag</h4>
</td>
<td>
#Html.ActionLink("Löschen", "EventDelete", new { id = e.EventID })
</td>
</tr>
}
</table>
</div>
I pass the id to the controller in the ActionLink and call the EventDelete:
[Authorize]
public ActionResult EventDelete(int id)
{
repevent.Delete(id);
return RedirectToAction("Main");
}
Now i have the id of the event and can do whatever i want. (In my case, i delete the event with the associated id.
public void Delete(int id)
{
using (KiGaDBEntities db = new KiGaDBEntities())
{
Event event = db.Event.SingleOrDefault(e => e.EventID == id);
if (event != null)
{
db.Event.Remove(event);
db.SaveChanges();
}
}
}
I hope that helps you!