Export Aspx View Page HTML Table Data to Excel File - excel

In my MVC3 Web application I have a aspx main view page and a partial View Page. My table is in Partial view. I have also applied Table sorter and other table css to it. Now I want to export data from this table to excel. I tried so many ways but it didn't worked for me. Can anyone Help Me Please...
Code of my partial view is:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>>" %>
<!-- for table sorter and table Pager -->
<script src="../../__jquery.tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
<script src="../../__jquery.tablesorter/jquery.tablesorter.widgets.js" type="text/javascript"></script>
<script src="../../__jquery.tablesorter/jquery.tablesorter.pager.js" type="text/javascript"></script>
<script type ="text/javascript" id="js">
$(function () {
// **********************************
// Description of ALL pager options
// **********************************
var pagerOptions = {
// target the pager markup - see the HTML block below
container: $(".pager"),
// use this url format "http:/mydatabase.com?page={page}&size={size}&{sortList:col}"
ajaxUrl: null,
// process ajax so that the data object is returned along with the total number of rows
// example: { "data" : [{ "ID": 1, "Name": "Foo", "Last": "Bar" }], "total_rows" : 100 }
ajaxProcessing: function (ajax) {
if (ajax && ajax.hasOwnProperty('data')) {
// return [ "data", "total_rows" ];
return [ajax.data, ajax.total_rows];
}
},
// output string - default is '{page}/{totalPages}'
// possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
output: '{startRow} to {endRow} ({totalRows})',
// apply disabled classname to the pager arrows when the rows at either extreme is visible - default is true
updateArrows: true,
// starting page of the pager (zero based index)
page: 0,
// Number of visible rows - default is 10
size: 10,
// if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty
// table row set to a height to compensate; default is false
fixedHeight: true,
// remove rows from the table to speed up the sort of large tables.
// setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
removeRows: false,
// css class names of pager arrows
cssNext: '.next', // next page arrow
cssPrev: '.prev', // previous page arrow
cssFirst: '.first', // go to first page arrow
cssLast: '.last', // go to last page arrow
cssGoto: '.gotoPage', // select dropdown to allow choosing a page
cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed
cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option
// class added to arrows when at the extremes (i.e. prev/first arrows are "disabled" when on the first page)
cssDisabled: 'disabled' // Note there is no period "." in front of this class name
};
// Extend the themes to change any of the default class names ** NEW **
$.extend($.tablesorter.themes.jui, {
// change default jQuery uitheme icons - find the full list of icons here: http://jqueryui.com/themeroller/ (hover over them for their name)
table: 'ui-widget ui-widget-content ui-corner-all', // table classes
header: 'ui-widget-header ui-corner-all ui-state-default', // header classes
footerRow: '',
footerCells: '',
icons: 'ui-icon', // icon class added to the <i> in the header
sortNone: 'ui-icon-carat-2-n-s',
sortAsc: 'ui-icon-carat-1-n',
sortDesc: 'ui-icon-carat-1-s',
active: 'ui-state-active', // applied when column is sorted
hover: 'ui-state-hover', // hover class
filterRow: '',
even: 'ui-widget-content', // odd row zebra striping
odd: 'ui-widget-content' // even row zebra striping
});
// call the tablesorter plugin and apply the ui theme widget
$("table").tablesorter({
theme: 'jui', // theme "jui" and "bootstrap" override the uitheme widget option in v2.7+
headerTemplate: '{content} {icon}', // needed to add icon for jui theme
// widget code now contained in the jquery.tablesorter.widgets.js file
widgets: ['uitheme', 'zebra'],
widgetOptions: {
// zebra striping class names - the uitheme widget adds the class names defined in
// $.tablesorter.themes to the zebra widget class names
zebra: ["even", "odd"]
// set the uitheme widget to use the jQuery UI theme class names
// ** this is now optional, and will be overridden if the theme name exists in $.tablesorter.themes **
// uitheme : 'jui'
}
})
// bind to pager events
// *********************
.bind('pagerChange pagerComplete pagerInitialized pageMoved', function (e, c) {
var msg = '"</span> event triggered, ' + (e.type === 'pagerChange' ? 'going to' : 'now on') +
' page <span class="typ">' + (c.page + 1) + '/' + c.totalPages + '</span>';
$('#display')
.append('<li><span class="str">"' + e.type + msg + '</li>')
.find('li:first').remove();
})
// initialize the pager plugin
// ****************************
.tablesorterPager(pagerOptions);
});
</script>
<!-- end table sorter and table Pager -->
<table class="tablesorter" id="ResultList">
<thead id="headers">
<tr>
<th>
CRMId
</th>
<th>
Territory
</th>
<th>
Doctor(MDLNo)
</th>
<th>
Requester
</th>
<th>
Suggester
</th>
<th>
Division
</th>
<th>
Estimated
</th>
<th>
Actual
</th>
<th>
Priority
</th>
<th>
Notation
</th>
<th>
Deadline
</th>
<th>
ExecutedDate
</th>
<th>
CreatedDate
</th>
<th>
CRM State
</th>
<th>
Service State
</th>
</tr>
</thead>
<tbody>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink(((int)item.Id).ToString(), "DetailsCRMRequest", "CRM", new { Id = item.Id, controllerName = "FilterCRMRequest", actionName = "Index" }, null)%>
<%--<%: Html.DisplayFor(modelItem => item.Id) %>--%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Territory_Name) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Request_For_Name) %> (<%: Html.DisplayFor(modelItem => item.Request_For_Id) %>)
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Requester_Name) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Suggester_Name) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Division_Name) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Estimated_Amount) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Actual_Amount) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Compute_Priority) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.CRM_Notation_Name) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Deadline) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Executed_Date) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Date_Created) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Compute_CRM_State) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Compute_Service_State) %>
</td>
</tr>
<% } %>
</tbody>
<tfoot>
<tr class="pager" align="center">
<td colspan="15">
<img src="../../Content/images/first.png" class="first" alt="First" />
<img src="../../Content/images/prev.png" class="prev" alt="Prev" />
<span class="pagedisplay"></span> <!-- this can be any element, including an input -->
<img src="../../Content/images/next.png" class="next" alt="Next" />
<img src="../../Content/images/last.png" class="last" alt="Last" />
<select class="pagesize" title="Select page size">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
<select class="gotoPage" title="Select page number"></select>
</td>
</tr>
</tfoot>
</table>
I have already tried this : this works but gives me css in Excel file and 5 td fields from all 50 records result...
function Export(e) {
window.open('data:application/vnd.ms-excel,' + $('#ResultList').html());
e.preventDefault();
}
and this : it doesn't worked totally...
function Export() {
alert("called function");
str = "";
var myTableHead = document.getElementById('headers');
var rowCount = myTableHead.rows.length;
var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
alert("before for");
for (var i = 0; i < rowCount; i++) {
for (var j = 0; j < colCount; j++) {
str = myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i + 1, j + 1).Value = str;
}
}
alert("done");
}

Related

How to get values dynamically from a collection in a model in Razor Pages?

I'm trying to render lists of elements dynamically in ASPNETCore Razor Pages but I can't find the way to show the values of properties using Display Helper. M
<table class="table datatable">
<thead>
<tr>
#foreach (var item in Model.GetFieldNamesForList())
{
<th>
#Html.DisplayName(item)
</th>
}
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.School) {
<tr>
#foreach (var propertyName in Model.GetFieldNamesForList())
{
<td>
// How to use #Html.Display using item from Model.School and the propertyName
</td>
}
<td>
<a asp-page="./Edit" asp-route-id="#item.Id" class="btn btn-primary btn-sm"><i class="material-icons md-16">edit</i></a>
<a asp-page="./Details" asp-route-id="#item.Id" class="btn btn-primary btn-sm"><i class="material-icons md-16">visibility</i></a>
<button action="submit" asp-page-handler="Delete" asp-route-id="#item.Id" class="btn btn-danger btn-sm"><i class="material-icons md-16">delete</i></button>
</td>
</tr>
}
</tbody>
</table>
In the meantime, I use reflection directly, but I would prefer use the Display method from helpers.
#item.GetType().GetProperty(propertyName).GetValue(item, null)

Loading a Partial view which has a complex model of many sub models into a jquery ui tab

I get an error when loading a particular view via an Html.action call to an action and Controller, into a jquery Tab.
The other View is loaded successfully via an HTML.Partial call.
How do I get this other particular partial loaded please.
The tab where the error happens is tab4.
The commented out HTML.Partial call works to a point but when it loads that Partial (User), which has multiple models in it's containing model,..those other models are null and it's iteration over them crashes.
(That partial is beneath the first block of code.)
If I try load it from an action Call, then
the JQuery function ("$#tabs").tabs crashes with ".tabs" is undefined
TIA
Code:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Tabs - Content via Ajax</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function ()
{
$("#tabs").tabs({
beforeLoad: function (event, ui)
{
ui.jqXHR.fail(function ()
{
ui.panel.html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo.");
});
}
});
});
</script>
<div id="tabs">
<ul>
<li>Person Detail</li>
<li>Addresses</li>
<li>Role Detail</li>
<li>User Detail</li>
</ul>
<div id="tabs-1">
#*#Html.Partial("~/Views/Person/Index.cshtml")*#
</div>
<div id="tabs-2">
#*#Html.Partial("~/Views/Address/Index.cshtml")*#
</div>
<div id="tabs-3">
#Html.Partial("~/Views/IdentityRole/List.cshtml", new List<Catalyst.Shared.IdentityRole>())
</div>
<div id="tabs-4">
#Html.Action("List", "User");
#*#Html.Partial("~/Views/User/List.cshtml", new Catalyst.Mvc.IdentityUserPersonViewModel())*#
</div>
</div>
The Partial which I want to load, but needs data, which I think would work if I called the Action as opposed to calling the Partial.
#model Catalyst.Mvc.IdentityUserPersonViewModel
#{
ViewBag.User = "List";
}
<div class="panel panel-default" style="width:1400px !important;text-align:center ">
<div class="panel-heading">
<h3>Users</h3>
</div>
<div class="panel-body">
<div style="text-align:right;">#Html.ActionLink("Add", "Create", null, new { #class = "btn btn-default" })</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
UserName
</th>
<th>
Password
</th>
<th>
Title
#*#Html.DisplayNameFor(model => model.)*#
</th>
<th>
FirstName
#*#Html.DisplayNameFor(model => model.)*#
</th>
<th>
LastName
</th>
<th>
PhoneNumber
</th>
<th>
Email
</th>
<th>
Company and Branch
</th>
<th></th>
<th></th>
</tr>
</thead>
#for (var i = 0; i < Model.identityUsers.Count(); i++)
{
<tr>
<td>
<a href="#Url.Action("Edit", "User" , new {id=Model.UserPersons[i].UserPersonId})">
#Html.DisplayFor(x => Model.identityUsers[i].UserName)
</a>
</td>
<td>
<a href="#Url.Action("Edit", "User" , new {id=Model.UserPersons[i].UserPersonId})">
#Html.EditorFor(x => Model.identityUsers[i].PasswordHash, new { htmlAttributes = new { #class = "form-control", placeholder = "Password", Type = "password" } })
</a>
</td>
<td>
<a href="#Url.Action("Edit", "User" , new {id=Model.UserPersons[i].UserPersonId})">
#Html.DisplayFor(x => Model.UserPersons[i].Title)
</a>
</td>
<td>
<a href="#Url.Action("Edit", "User" , new {id=Model.UserPersons[i].UserPersonId})">
#Html.DisplayFor(x => Model.UserPersons[i].Name)
</a>
</td>
<td>
<a href="#Url.Action("Edit", "User" , new {id=Model.UserPersons[i].UserPersonId})">
#Html.DisplayFor(x => Model.UserPersons[i].Surname)
</a>
<td>
#*<a href="#Url.Action("Edit", "User" , new {id=Model.identityUsers[i].Id})">
#Html.DisplayFor(x => Model.identityUsers[i].Email)
</a>*#
</td>
<td>
#*<a href="#Url.Action("Edit", "User" , new {id=Model.identityUsers[i].Id})">
#Html.DisplayFor(x => Model.identityUsers[i].PhoneNumber)
</a>*#
</td>
<td>
#*<a href="#Url.Action("Edit", "User" , new {id=item.ID})">
#Html.DisplayFor(x => item.PhoneNumber)
</a>*#
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id =
Model.identityUsers[i].Id })
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { id =
Model.identityUsers[i].Id })
</td>
</tr>
}
</table>
</div>
The Controller of the view I can't get laoded
public class UserController : Controller
{
private IdentityUserBo identityUserBo;
private PersonBo personBo;
private IdentityUserPersonBo identityuser_personBo;
IdentityUserPersonViewModel model = new IdentityUserPersonViewModel();
public UserController(IdentityUserBo boIdentityUser, PersonBo boPerson, IdentityUserPersonBo boIdentityUserPerson )
{
this.identityUserBo = boIdentityUser ?? throw new ArgumentNullException("boIdentityUser");
this.personBo = boPerson ?? throw new ArgumentNullException("boPerson");
this.identityuser_personBo = boIdentityUserPerson ?? throw new ArgumentNullException("boIdentityUserPerson");
}
public ActionResult Index()
{
return RedirectToAction("List");
}
public ActionResult List()
{
ExBool result = null;
IdentityUserPersonViewModel userPersonViewModel = new IdentityUserPersonViewModel();
result = this.identityUserBo.List(out List<IdentityUser> identityUsers);
if (!result.Success) throw new Exception(result.Messages);
if (identityUsers == null) throw new Exception("Could not load IdentityUsers");
// Ideally see detail eg branch and tel and email from their respective tables
userPersonViewModel.identityUsers = identityUsers;
//Get the Persons, match these via Person.Id -> IdentityUserPerson.FKPersonId + IdentityUserPerson.FKUserId -> IdentityUser.ID
List<Person> persons = null;
result = this.personBo.List(out persons);
//IdentityUserPersonViewModel viewModel = new IdentityUserPersonViewModel();
userPersonViewModel.persons = persons;
// Get the IdentityUserPersons
List<IdentityUserPerson> identityUserPersons = null;
result = this.identityuser_personBo.List(out identityUserPersons);
IdentityUserPerson UPRec = new IdentityUserPerson();
Person PRec = new Person();
userPersonViewModel.UserPersons = new List<UserPerson>();
foreach (IdentityUser rec in userPersonViewModel.identityUsers)
{
UPRec = identityUserPersons.Find(x => x.FKUserID == rec.Id);
if (UPRec != null)
{
//UserId, UserPersonId, + Person.Id + Person.Name + Person.Surname
PRec = persons.Find(y => y.ID == UPRec.FKPersonID);
UserPerson UsrPers = new UserPerson();
UsrPers.UserId = rec.Id;
UsrPers.UserPerson_FKPersonId = UPRec.FKPersonID;
UsrPers.UserPerson_FKUserId = UPRec.FKUserID;
UsrPers.Name = PRec.FirstName;
UsrPers.Surname = PRec.LastName;
UsrPers.Title = PRec.TitleCode;
userPersonViewModel.UserPersons.Add(UsrPers);
}
else
{
UserPerson UsrPers = new UserPerson();
userPersonViewModel.UserPersons.Add(UsrPers);
}
}
return View(userPersonViewModel);
}
Check your console what error you got.
and also change this in tab4
#{
#Html.Partial("List", new Catalyst.Mvc.IdentityUserPersonViewModel())
}

Jquery datatable not working for first row in colspan

I tried to bind dynamically partial view its working but for jquery
datatable against first row what I specified below its not working.
#model IEnumerable<PurModelClass>
<table id="stock-audit-table" class="table table-striped table-bordered dt-responsive nowrap">
<thead>
<tr>
#*<th>Purchase From</th>
<th>Purchase Date</th>*#
<th>Item Name</th>
<th>Qty</th>
<th>Unit</th>
<th>Cost</th>
<th>Net Amount</th>
<th>Discount</th>
<th>Vat</th>
<th>Gross</th>
</tr>
</thead>
<tbody id="stock-audit-tbody">
#foreach (var item in Model)
{
<tr><td colspan="8">Invoice No: #item.PurInvNo Inv Date: #($"{#item.PurDate:MMM-dd-yyyy}") Vendor: #item.VendorName </td></tr>
foreach (var detail in item.PurDetails)
{
<tr>
<td>#detail.StockName</td>
<td>#detail.PurQty</td>
<td>#detail.UnitName</td>
<td>#detail.UnitPrice</td>
<td>#detail.Total</td>
<td>#detail.Discount</td>
<td>#detail.VAT</td>
<td>#detail.NetAmount</td>
</tr>
}
}
</tbody>
<tfoot>
</tfoot>
</table>
This the datatable script, is there any way to implement jquery datatable by demanding specific row with colspan properties.
<script type="text/javascript">
$(document)
.ready(function() {
$('#stock-audit-table').DataTable({
"autoWidth": false,
"order": [[0, "desc"]]
});
}
);
</script>
Try the rowGroup extension. You can use startRender and endRender to customize the summary data
$('#stock-audit-table').DataTable({
"autoWidth": false,
"order": [[0, "desc"]],
"rowGroup": {
dataSrc: 0,
startRender: function(groupName){
return $('<tr/>').append("<td colspan="8">TODO put data here</td>");
}
}
});
<tbody id="stock-audit-tbody">
#foreach (var item in Model)
{
foreach (var detail in item.PurDetails)
{
<tr>
<td>
<!-- Define a key to be referenced by the
'datasrc' property in dataTables -->
#item.GroupName
</td>
<td>#detail.StockName</td>
<td>#detail.PurQty</td>
<td>#detail.UnitName</td>
<td>#detail.UnitPrice</td>
<td>#detail.Total</td>
<td>#detail.Discount</td>
<td>#detail.VAT</td>
<td>#detail.NetAmount</td>
</tr>
}
}
</tbody>

Pass Id to ActionMethod

I have a Delete button inside my table and I m trying to delete the selected Row.
The problem is that I always get in the post method a null ID
<div>
<table class="table">
<thead>
<tr>
<th>Role Name</th>
<th>Action</th>
</tr>
</thead>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#using (Html.BeginForm("Delete","Role", new { id = item.Id },FormMethod.Post))
{
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
</div>
}
</td>
</tr>
}
</table>
In My Controller
// POST: Jobs/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult Delete(int id)
{
IdentityRole role = _context.Roles.Find(id);
_context.Roles.Remove(role);
_context.SaveChanges();
return RedirectToAction("Index");
}
Any time I click on the button the id is null
From your comments, the html generated in <form> tags is
action="/Role/Delete/b1bc13ca-a855-48b0-90e2-9e5fc081ac86"
meaning that the Id property of your model is typeof Guid. Change the POST method signature to
public ActionResult Delete(Guid id)

Edit in view page or index.cshtml in MVC

I am using MVC 5 and Entity framework 6 (Database First) in my application.
I need to update "value" field in View page\index.cshtml.
Is it possible to use #Html.EditorFor to edit Value field for each Item on single button click?
Here is the code in index.cshtml
<table>
<tr>
<th>
Number
</th>
<th>
Name
</th>
<th>
Value
</th>
<th>
Description
</th>
</tr>
foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.number)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td>
#Html.EditorFor(modelItem => item.value)
#*#Html.ValidationMessageFor(modelItem => item.value) *#
</td>
<td>
#Html.DisplayFor(modelItem => item.description)
</td>
#* <td>
#Html.ActionLink("Edit", "Edit", new { id=item.id })
</td>*#
</tr>
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
On clicking Save button I should update the data in Value field for any number of rows.
It's done in Database First so action for Edit,View,Details are included in Controller.
You'll have to put everything in a to post the details to the server, then you can manage the posted elements. You'll post a list of itens. Maybe this will help you: How can I post a list of items in MVC

Resources