Convert an expanded html table row to jquery datatable - javascript

I have a Jquery datatable with rows which expand into another table. The subtable displays perfectly but how do i render this table which is returned by a View into a datatable ?
Sub table view
#model IEnumerable<Virtual_Machines.Process>
#{
ViewBag.Title = "VM Monitor";
Layout = "";
}
<script type="text/javascript">
var oTable1;
/* Initialize table and make first column non-sortable*/
oTable1 = $('#innerproc').dataTable({
"bJQueryUI": true,
"aoColumns": [
{ "bSortable": false, "bSearchable": false },
null,
null,
null
]
});
</script>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table" id="innerproc">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.ProcessName)
</th>
<th>
#Html.DisplayNameFor(model => model.PID)
</th>
<th>
#Html.DisplayNameFor(model => model.status)
</th>
<th>
#Html.DisplayNameFor(model => model.date)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProcessName)
</td>
<td>
#Html.DisplayFor(modelItem => item.PID)
</td>
<td>
#Html.DisplayFor(modelItem => item.status)
</td>
<td>
#Html.DisplayFor(modelItem => item.date)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
As you can see , i tried using javascript to get a reference to the table via id attribute and then convert it to a datatable. This throws an error : Uncaught TypeError: $(...).datatable is not a function
I also tried embedding the code in the #section so that it runs when the doc.ready method is called in the main layout file, this too doesn't work. I think i'm not sure as to where to place the code to convert this table to a datatable as it is being returned by a view.

Related

How to make a number with commas as thousands separator in table, javascript

I want to print an integer with a comma as a separator, for example 10,234,234
in the price column.
I have made the function, but I am a little confused how to make it in the table. Below is my code
<table class="table">
<tr>
<th> Item</th>
<th>Price</th>
</tr>
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
<tr>
<td></td>
<td> #Html.EditorFor(model => model.TotalPrice, new { htmlAttributes = new { #class = "form-control", #onchange = "validationCheck();", #readonly = "readonly" } }) </td>
</tr>
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
You need to get all second td elements in the table and then update the content using the code.
<table class="table" id="table">
<!-- set id to get table^^^^^^^^---->
<tr>
<th> Item</th>
<th>Price</th>
</tr>
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// get all second tds
[...document.querySelectorAll('#table tr > td:nth-child(2)')].forEach(e => {
// get text content and update
e.textContent = numberSeparator(e.textContent.trim());
})
</script>
FYI : It's always better to do it from the backend side if possible. There may be some functions available in your backend framework/programming language.
UPDATE : In your updated code you are creating an input so get input element update it's value.
<table class="table">
<tr>
<th> Item</th>
<th>Price</th>
</tr>
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice)</td>
</tr>
}
<tr>
<td></td>
<td> #Html.EditorFor(model => model.TotalPrice, new { htmlAttributes = new { #class = "form-control", #onchange = "validationCheck();", #readonly = "readonly" } }) </td>
</tr>
</table>
<script>
function numberSeparator(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// get all second tds
[...document.querySelectorAll('#table tr > td:nth-child(2) input')].forEach(e => {
// get text content and update
e.value = numberSeparator(e.value.trim());
})
</script>
You can use toLocaleString to display a number with comma separators
let num = 1000000
let display = num.toLocaleString('us-US')
console.log(display) // 1,000,000
I suspect your code could work like this
#foreach (SHOP.ViewModels.ItemViewModel item in Model.Itemss)
{
<tr>
<td> #Html.DisplayFor(modelitem => item.itemName) </td>
<td> #Html.DisplayFor(modelitem => item.itemPrice.toLocaleString('us-US'))</td>
</tr>
}

How to filter data in html table by changing option in drop down in asp.net mvc?

It's been days since I started to study MVC programming and honestly I'm still coping up to new environment of MVC.
In my project, I started to create a data table that display the data in my database using these codes.
This is my codes in view and controller. This part runs very well.
<table id="table1" >
<thead>
<tr>
<th>id</th>
<th>title </th>
<th>
description
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.id)
</td>
<td>
#Html.DisplayFor(modelItem => item.title)
</td>
<td>
#Html.DisplayFor(modelItem => item.description)
</td>
</tr>
}
</tbody>
</table>
}
var charts = (from p in db.pmTA_ProjectCategory
select new
{
id = p.id,
title = p.title,
description = p.description,
}).ToList()
.Select(x => new pmTA_ProjectCategory()
{
id = x.id,
title = x.title,
description = x.description,
});
return View(charts.ToList());
But I noticed that I need to filter my data using dropdown so I added drop down to my View again.
This is my code in view and controller to display the dropdown and data inside the dropdown.
<div>
#Html.DropDownList("projectcat", ViewBag.proj as SelectList, "Select...", new {
#class = "form-control" })
</div>
var data1 = from p in db.pmTA_ProjectCategory
select new
{
id = p.id,
title = p.title,
description = p.description
};
SelectList list = new SelectList(data1, "id", "title");
ViewBag.proj = list;
when it comes to displaying the data inside the dropdown it runs again smoothly.
My problem is, I need to filter the data of data table using dropdown automatically. I mean, when I selected the value of dropdown the data table must show the data corresponds to the selected value in dropdown
I created codes in javascript to filter the data of datatable using dropdown.
This is the code:
<script>
$(document).ready(function () {
var table = $("#table1").DataTable();
$("#projectcat").change(function () {
table.search(this.value).draw();
});
});
</script>
But the data in my data table is not responding and not functioning, when I selected the data in dropdown the datatable can't filter.
1) Your view should be of strongly type of IEnumerable<ProjectCategory>
2) Add drop down to your view
<div class="dropdown">
#Html.DropDownList("id", (List<SelectListItem>)ViewBag.proj, "--Select id--", new { #onchange = "CallChangefunc(this.value)" })
</div>
3) Add partial view of IEnumerable<ProjectCategory> in your view. When you adding partial view then check it as Create as a partial view.
The name of your partial view is _GetItem.cshtml
The content of partial view
<table id="table1" >
<thead>
<tr>
<th>id</th>
<th>title </th>
<th>
description
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.id)
</td>
<td>
#Html.DisplayFor(modelItem => item.title)
</td>
<td>
#Html.DisplayFor(modelItem => item.description)
</td>
</tr>
}
</tbody>
</table>
And call this partial view in your view just below to your drop down that you added earlier.
<div id="myPartialView">
#{Html.RenderPartial("_GetItem", Model);}
</div>
4) You action method in controller would be
public ActionResult Index()
{
var charts = db.ProjectCategories.ToList();
List<SelectListItem> dropDownItems = charts.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
ViewBag.proj = dropDownItems;
return View(charts);
}
5) Add ajax call to your view that called when you change any option in your drop down
<script>
function CallChangefunc(id) {
$.ajax({
url: "#Url.Action("GetItem", "Default")",
data: { id: id },
type: "Get",
dataType: "html",
success: function (data) {
console.log(data);
//Whatever result you have got from your controller with html partial view replace with a specific html.
$("#myPartialView").html( data ); // HTML DOM replace
}
});
}
</script>
6) And finally your ajax call hit below action method that can render only partial view
public PartialViewResult GetItem(int id)
{
var charts = db.ProjectCategories.ToList();
var model = charts.Where(x => x.id == id).ToList();
return PartialView("_GetItem", model);
}
Current status :
You have created a drop down list id='projectcat'
Datatable $("#table1") is not responding on change event
Solution :
Your code looks correct there is nothing wrong with it.
Running same kind of example below is working correctly
Make sure there is no other javascript error blocking this code
Apply debugger inside $("#projectcat").change(function () { debugger; }); to debug code in developer toolbar
Check below example, changing drop down value its also filtering datatable:
$(document).ready(function () {
var table = $("#table1").DataTable();
$("#projectcat").change(function () {
console.log('Groing for folter : ' + this.value);
table.search(this.value).draw();
});
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
<p>Change datatable filter value : </p>
<select id="projectcat">
<option>Rhona</option>
<option>Colleen</option>
<option>Jena</option>
<option>Tiger</option>
</select>
<hr />
<table id="table1" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>$320,800</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>$327,900</td>
</tr>
<tr>
<td>Colleen Hurst</td>
<td>$205,500</td>
</tr>
<tr>
<td>Sonya Frost</td>
<td>$103,600</td>
</tr>
<tr>
<td>Tiger Kennedy</td>
<td>$313,500</td>
</tr>
<tr>
<td>Rhona Kennedy</td>
<td>$12,900</td>
</tr>
</tbody>
</table>

Display Details for Individual Items inside Tooltip on Mouse Hover

I am trying to display the details within a tooltip for each item in my index view. I would like the tooltip to appear when the mouse hovers over an items name. Currently I have some javascript and an view to go along with it. Any help or recommendations would be greatly appreciated!
Details Javascript:
$(document).load(function () {
for (var count = 0; count < 10; count++) {
$(document).tooltip({
items: "#j" + count,
content: function () {
return $("#i" + count).text();
}
});
};
});
Index View:
<table class="table">
<tr>
<th>
#Html.ActionLink("Software Name", "Index", new { sortOrder = ViewBag.SoftNameSort, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("License Type", "Index", new { sortOrder = ViewBag.LicenseType, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("End Date", "Index", new { sortOrder = ViewBag.EndDateSort, currentFilter = ViewBag.CurrentFilter })
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<noscript id="i#(count)">#Html.Partial("_SoftwareDetails", (WBLA.Models.SoftwareLicense)item)</noscript>
<td id="j#(count)">
#Html.DisplayFor(modelItem => item.SoftwareName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LicenseType)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.SoftwareID }) |
#Html.ActionLink("Details", "Details", new { id = item.SoftwareID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.SoftwareID })
</td>
</tr>
count++;
}
</table>
** EDIT **
I forgot to mention what I would like to show inside the tooltip. I would like to load a partial, which displays the relevant information for each item in my index view.
Partial Details View:
#model WBLA.Models.SoftwareLicense
<table>
<tr>
<th>
#Html.LabelFor(model => model.SoftwareName)
</th>
<td>
#Html.DisplayFor(model => model.SoftwareName)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.SoftwareKey)
</th>
<td>
#Html.DisplayFor(model => model.SoftwareKey)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.Price)
</th>
<td>
#Html.DisplayFor(model => model.Price)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.DepartmentName)
</th>
<td>
#Html.DisplayFor(model => model.DepartmentName)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.LicenseFilePath)
</th>
<td>
#Html.DisplayFor(model => model.LicenseFilePath)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.LicenseType)
</th>
<td>
#Html.DisplayFor(model => model.LicenseType)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.StartDate)
</th>
<td>
#Html.DisplayFor(model => model.StartDate)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.EndDate)
</th>
<td>
#Html.DisplayFor(model => model.EndDate)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.NotifyTime)
</th>
<td>
#Html.DisplayFor(model => model.NotifyTime)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.ConsumerEmail)
</th>
<td>
#Html.DisplayFor(model => model.ConsumerEmail)
</td>
</tr>
<tr>
<th>
#Html.LabelFor(model => model.EntryEmail)
</th>
<td>
#Html.DisplayFor(model => model.EntryEmail)
</td>
</tr>
</table>
* EDIT 8/03/2016 *
The title for the tooltip-tagged displays, however, my partial will not load within the tooltip.
Updated SoftwareDetails.js:
$(function () {
var url = '#Url.RouteUrl(new{ action="SoftwareDetails", controller="SoftwareLicense"})';
$(document).tooltip({
items: "td.myToolTips",
content: function (callback) {
$.get(url + "?id=" + $(this).data("id"))
.done(function (r) {
callback(r);
});
}
});
});
Updated Index View:
<table class="table">
<tr>
<th>
#Html.ActionLink("Software Name", "Index", new { sortOrder = ViewBag.SoftNameSort, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("License Type", "Index", new { sortOrder = ViewBag.LicenseType, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.ActionLink("End Date", "Index", new { sortOrder = ViewBag.EndDateSort, currentFilter = ViewBag.CurrentFilter })
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td class="myToolTips" data-id="#item.SoftwareID" title="Loading in a second..">
#item.SoftwareName
</td>
<td>
#Html.DisplayFor(modelItem => item.LicenseType)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.SoftwareID }) |
#Html.ActionLink("Details", "Details", new { id = item.SoftwareID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.SoftwareID })
</td>
</tr>
//count++;
}
</table>
Updated SoftwareDetails Action:
public ActionResult SoftwareDetails(int id)
{
SoftwareLicense temp = db.SoftwareLicenses.Find(id);
return PartialView("SoftwareDetails", temp);
}
Result from URL Test (For Partial):
Partial Test
You do not need to render the tool tip partial view for all items when the page loads. You may get it on as needed basis. You can do this by making an ajax call and passing a unique id for the record user is hovering on currently.
Start by keeping a data attribute in your tr for the unique id.
#foreach (var item in Model)
{
<tr class="myToolTips" data-id="#item.SoftwareID" title="#item.SoftwareName">
<td>#item.SoftwareName</td>
</tr>
}
and you can enable tooltip for the table rows with the css class myToolTips.
$(function () {
$(document).tooltip({
items: "tr.myToolTips",
content: function (callback) {
$.get('/Home/SoftwareDetails/' + $(this).data("id"))
.done(function (r) {
callback(r);
});
}
});
});
Assuming you have an action method called SoftwareDetails which accepts the id and return the partial view
public ActionResult SoftwareDetails(int id)
{
return Content("Toolip for "+id);
// to do : Return the partial view for the markup you want (for the id)
}

Live search partialview loads as full view with Ajax.BeginForm

I´m trying to create a live search mechanism using Ajax and partialviews. The idea is that the main view is simply a text box without submit button (this is a main requirement for the program). The user types in the box and an onchange command activates a javascript function which submits the form into a controller. The controller will then make a database search and return a partialview filled with a table of results to substitute a div in the original view.
My problem is that the partialview with the results loads as a full view, over the index and search views.
These are my code snippets starting with the index view.
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="buscar">
#Html.Action("Buscar", "Reportes")
</div>
<div id="encontrar-form">
</div>
Now the partialview with the search button
#model IEnumerable<ProyectoTamaulipas.Reporte>
<script>
function showRes () {
document.getElementById("forma").submit();
}
</script>
<div>
<br />
<br />
<h2>Haga una búsqueda por número de folio</h2>
<p>
#using (Ajax.BeginForm("Buscar", "Reportes", FormMethod.Post, new AjaxOptions(){
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "encontrar-form"
}, new { id = "forma" }))
{
<input type="text" name="numero" onchange="showRes()" />
}
</p>
</div>
Now the relevant controllers
[HttpGet]
public ActionResult Buscar()
{
return PartialView("First");
}
[HttpPost]
public PartialViewResult Buscar(string numero)
{
if (numero != null)
{
int numeroF = 0;
//var query = (from a in db.Reporte
// where SqlMethods.Like(a.Calle1, "%" + parm + "%")
// select a).ToList();
List<Reporte> query = null;
if (Int32.TryParse(numero, out numeroF))
{
query = (from a in db.Reporte
where a.Folio == numeroF
select a).ToList();
}
return PartialView("reporte", query);
}
ViewBag.Message = "no se encontraron resultados";
return PartialView("reporte");
}
Finally the results view.
#model IEnumerable<ProyectoTamaulipas.Reporte>
#ViewBag.Message
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.UCivil_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.ServicioID)
</th>
<th>
#Html.DisplayNameFor(model => model.Ubicacion)
</th>
<th>
#Html.DisplayNameFor(model => model.Calle1)
</th>
<th>
#Html.DisplayNameFor(model => model.Calle2)
</th>
<th>
#Html.DisplayNameFor(model => model.ColoniaID)
</th>
<th>
#Html.DisplayNameFor(model => model.Comentarios)
</th>
<th>
#Html.DisplayNameFor(model => model.EstatusID)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.UCivil_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ServicioID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Ubicacion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Calle1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Calle2)
</td>
<td>
#Html.DisplayFor(modelItem => item.ColoniaID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comentarios)
</td>
#*<td>
#Html.DisplayFor(modelItem => item.Fotografia)
</td>*#
<td>
#Html.DisplayFor(modelItem => item.EstatusID)
</td>
</tr>
}
</table>
I already tried changing several commands and verifying the instalation of my unobtrusive ajax as well as several other things. Sorry for the long question but I've been going at this for two workdays with no luck. Thanks for the help!
I solved it by calling the jquery.unobtrusive-ajax.js on layout intead of on individual views and changing the
document.getElementById("forma").submit();
for a
$("#forma").trigger("submit");
on the search function inside the search partialview called First.

Query Database Using JavaScript

I am fairly new to JavaScript and never used Ajax before. I want to add an OnClick to the Index.cshtml, so when a row is clicked, my code will query database (MSSQL)and return results.
I have two tables in database, User and Contact. The primary key in User, UID, is the foreign key in Contact. Here's my code:
Controller
private UserInfoEntities db = new UserInfoEntities();
public ActionResult Index(){
var users = from u in db.User orderby u.UID select u;
return View(users.ToList());
}
View
#<Info.Model.User>
<script type="text/javascript">
function showEmail() {
var tb = document.getElementById("users");
var rows = tb.rows;
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = (function() {
//some code that query Contact table using UID
// and return Contact.Email in a popup windows or something
});
}
}
</script>
<table class="table" id="users" onclick="showEmail()">
<tr>
<th>
#Html.DisplayNameFor(model => model.NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.UID)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.UID)
</td>
</tr>
Any help is appreciated!
try this;
<script type="text/javascript">
function showEmail() {
//some code that query Contact table using UID
// and return Contact.Email in a popup windows or something
}
</script>
<table class="table" id="users" >
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().UID)
</th>
</tr>
#foreach (var item in Model) {
<tr onclick="showEmail()">
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.UID)
</td>
</tr>
}

Categories

Resources