I have HTML table on the ASP.NET MVC View page. Now I have to export this table to Excel.
(1) I have used partial view (Inquiries.ascx) to display the table data from database (using LINQ to Entity)
(2) I also have used UITableFilter plugin to filter the records (Ex: http://gregweber.info/projects/demo/flavorzoom.html )
(3) At any point of time, I have to filter the visible records to Excel.
Appreciate your responses.
Thanks
Rita
Here is my View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mvc.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content2" ContentPlaceHolderID="cphHead" runat="server">
<script src="../../Scripts/jquery.tablesorter.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.uitablefilter.js" type="text/javascript"></script>
<script type="text/javascript">
//Load Partial View
$('#MyInquiries').load('/Home/Inquiries');
// To Apply Filter Expression using uiTableFilter plugin
$("#searchName").keyup(function() {
$.uiTableFilter($("#tblRefRequests"), this.value);
$("#tblRefRequests").tablesorter({ widthFixed: true, widgets: ['zebra'] });
});
//Export the HTML table contents to Excel
$('#export').click(function() {
//Code goes here
});
</script>
</asp:Content>
//Main Content
<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" runat="server">
<h2 class="pageName">View All Inquiries</h2>
<input type="submit" value="Export to Excel" id="export" />
<div id='MyInquiries'></div>
</asp:Content>
Strongly Typed Partial view user control (Inquiries.ascx) to generate table:
<table>
<tr><td valign ="middle">Filter Expression: <%= Html.TextBox("searchName")%></td></tr>
</table>
<table id="tblRefRequests" >
<thead>
<tr>
<th>Tx_ID</th>
<th>TX Date</th>
<th>Name</th>
<th>Email Address </th>
<th>Products</th>
<th>Document Name</th>
</tr>
</thead>
<tbody>
<% foreach (var item in Model) { %>
<tr>
<td visible =false><%= item.RequestID %></td>
<td><%= String.Format("{0:d}", item.RequestDate) %></td>
<td><%= item.CustomerName %></td>
<td><%= Html.Encode(item.Email) %></td>
<td><%= item.ProductName %></td>
<td><%= Html.Encode(item.DocDescription)%></td>
</tr>
<% } %>
</tbody>
</table>
Here is my Controller code to load the Inquiries partial view:
[HttpGet]
public PartialViewResult Inquiries()
{
var model = from i in myEntity.Inquiries
where i.User_Id == 5
orderby i.TX_Id descending
select new {
RequestID = i.TX_Id,
CustomerName = i.CustomerMaster.FirstName,
RequestDate = i.RequestDate,
Email = i.CustomerMaster.MS_Id,
DocDescription = i.Document.Description,
ProductName = i.Product.Name
};
return PartialView(model);
}
Try the jQuery plugin: table2csv. Use the argument, delivery:'value', to return the csv as a string.
Here is an implementation:
Add a regular html input button and a .NET HiddenField to the page
Add an onclick event to that button called "Export"
Create a javascript function, Export, that stores the return value of table2CSV() into the hidden field, and posts back.
The server receives the hiddenfield post data (the csv as a string)
The server outputs the string to the browser as a csv file
.
// javascript
function Export()
{
$('#yourHiddenFieldId').val() = $('#yourTable').table2CSV({delivery:'value'});
__doPostBack('#yourExportBtnId', '');
}
// c#
if(Page.IsPostBack)
{
if(!String.IsNullOrEmpty(Request.Form[yourHiddenField.UniqueId]))
{
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment; filename=TheReport.csv");
Response.Flush();
Response.Write(Request.Form[yourHiddenField.UniqueID]);
Response.End();
}
}
download components:npm install table-to-excel
https://github.com/ecofe/tabletoexcel
var tableToExcel=new TableToExcel();
document.getElementById('button1').onclick=function(){
tableToExcel.render("table");
};
document.getElementById('button2').onclick=function(){
var arr=[
['LastName','Sales','Country','Quarter'],
['Smith','23','UK','Qtr 3'],
['Johnson','14808','USA','Qtr 4']
]
tableToExcel.render(arr,[{text:"create",bg:"#000",color:"#fff"},{text:"createcreate",bg:"#ddd",color:"#fff"}]);
};
Related
Hi I have problem with my MVC application.
I would like click on ActionLink > load data from server > and insert data to div in same page.
But my code still loads content on new page and I don`t have idea why. Anybody to help me ?
This is my Index.cshtml in HomeController,
#model IEnumerable<Kango_kmen.KangoKmenWS.WSEntityInfo>
#Content.Script("jquery-1.9.1.min.js", Url)
#Content.Script("jquery.unobtrusive-ajax.min.js",Url)
#Content.Script("jquery.unobtrusive-ajax.js",Url)
#Content.Script("myScript.js",Url)
#section Entities{
<table>
<tr>
<th>
<input type="submit" value="zobrazit" />
</th>
<th>
iD
</th>
<th>
name
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Ajax.ActionLink("..", "CheckEntity", new { id = item.iD },
new AjaxOptions{ UpdateTargetId="properties",
HttpMethod="GET",
InsertionMode=InsertionMode.InsertAfter,
})
</td>
<td>
#Html.DisplayFor(modelItem => item.iD)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
</tr>
<tr>
<td>
<div id="properties">
</div>
</td>
</tr>
}
</table>
}
#section PropertyInfo{
<p>Property info</p>
}
#section Properties{
<p>properties</p>
}
And here is my Controller in HomeController
public PartialViewResult CheckEntity(int id)
{
var model = WSConnect.getEntityInfo(id);
if(model !=null){
return PartialView("CheckEntity", model.property);
}
var modell = new WSEntityInfo[0];
return PartialView("CheckEntity", modell);
}
and ChecktEntity is the Partial view but everytime I click on ActionLink controller load url: /Home/ChceckEntity/1000 for exmaple on view data on this new page "(
There are 2 things wrong with your code:
You have included the jquery.unobtrusive-ajax.js script twice, once the minified version and once the standard version. You should include it only once
The jquery.unobtrusive-ajax.js is not compatible with jquery 1.9.1 because one of the breaking changes in jQuery 1.9 is that the .live() method was removed and the jquery.unobtrusive-ajax.js script relies on it. If you look at your javascript console you would see the following error: The .live method is undefined.. So if you want to use the unobtrusive AJAX functionality in ASP.NET MVC you will have to downgrade the version of jQuery. For example the 1.8.3 version should be fine.
So:
#model IEnumerable<Kango_kmen.KangoKmenWS.WSEntityInfo>
#Content.Script("jquery-1.8.3.min.js", Url)
#Content.Script("jquery.unobtrusive-ajax.min.js", Url)
#Content.Script("myScript.js", Url)
Also please learn how to debug your javascript code. Use a tool such as FireBug or Chrome developer toolbar where all those errors will be shown.
Here is the code of my knockout template:
<script type="text/html" id="row-extension-template">
{{each items}}
<tr class="tr_element">
<td><span>${name}</span></td>
</tr>
{{/each}}
</script>
This piece of code is embedded in my jsp file.
When I see the html source-code generated by the server is look like this:
<tr class="tr_element">
<td><span></span></td>
</tr>
But I want this:
<tr class="tr_element">
<td><span>${name}</span></td>
</tr>
I want the text ${name} to be written in the html generated. How can I do that with Spring-mvc?
I have solved with this:
<script type="text/html" id="row-extension-template">
{{each items}}
<tr class="tr_element">
<td><span><%="${name}"%></span></td>
</tr>
{{/each}}
</script>
That way when I see the html source code I get:
<tr class="tr_element">
<td><span>${name}</span></td>
</tr>
Your page is loaded by using a Controller and RequestMapping in Spring. Find the method annotated with #RequestMapping that corresponds with your page. You then need to add the name to the model within that method.
model.addAttribute("name", "Some Name Value");
http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html
Write an object to the Model with key name, as in:
#RequestMapping("foo.do")
public String myHandler(Model model) {
String name = "something";
model.addAttribute("name", name);
return "foo";
}
I am trying to render a table, using EditorFor, and a partialview, I think.
I have a model with a List<> property defined like this:
public List<TransactionSplitLine> TransactionSplitLines { get; set; }
The idea is that a user selects a few drop downs and enters a value into an edit box, and clicks a button. The model goes back to the controller, and the controller adds the entered values to the List<>
[HttpPost]
public ActionResult AccountTransaction(AccountTransactionView model)
{
var reply = CreateModel(model);
if (model.CategoryIds != null)
{
foreach (var c in model.CategoryIds)
{
reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = int.Parse(c) });
}
}
reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = 1 });
return View("AccountTransaction", reply);
}
Ignore the CreateModel. It simply sets up some data. Also, I am hardcoding data. This will eventually come from some form values.
The model is then returned to the same screen, allowing the user to ender more data. Any items in the List<> are read and a Table is rendered. I also have to store the current listen item values in hidden fields, so that they can be submitted back, along with the new data entered, so that the list can grow each time the user adds data.
The view is defined like this:
<table width="600">
<thead>
<tr class="headerRow">
<td>
Category
</td>
<td>
Sub Category
</td>
<td>
Amount
</td>
</tr>
</thead>
<tbody>
<%=Html.EditorFor(m=>m.TransactionSplitLines) %>
</tbody>
</table>
This is my first attempt with EditorFor...
My View is in a folder 'Views/BankAccount/AccountTransaction.aspx
I have created a ascx in Views/Shared/TransactionSplitLines.ascx
The code for the ascx is like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BudgieMoneySite.Models.TransactionSplitLine>" %>
<tr>
<td>
<%=Model.Category %>
<%=Html.HiddenFor(x => x.CategoryId)%>
</td>
<td>
<%=Model.SubCategory %>
<%=Html.HiddenFor(x => x.SubCategoryId)%>
</td>
<td>
<%=Model.Amount %>
<%=Html.HiddenFor(x => x.AmountValue)%>
</td>
</tr>
This is data
The 'This is data' is just test stuff, which is never rendered.
When I run this, all that happens is that my output is rendered as:
<table width="600">
<thead>
<tr class="headerRow">
<td>
Category
</td>
<td>
Sub Category
</td>
<td>
Amount
</td>
</tr>
</thead>
<tbody>
Test Category
</tbody>
</table>
It seems like the ascx isn't being used? I'd expect to see the 'This is data' text. But, nothing. Hopefully you can see an obvious fault?
Your editor template should be either:
~/Views/Shared/EditorTemplates/TransactionSplitLine.ascx
or:
~/Views/BankAccount/EditorTemplates/TransactionSplitLine.ascx
The name of the ascx is always the type name of the collection item (TransactionSplitLine and not TransactionSplitLines) and it should be situated at ~/Views/Shared/EditorTemplates or ~Views/ControllerName/EditorTemplates.
Or if you want to use a custom editor template name:
<%= Html.EditorFor(m=>m.TransactionSplitLines, "~/Views/foo.ascx") %>
Or use UIHintAttribute on your model.
I am trying to delete a record being displayed in a table on my ManageUser view using a sub-form, thus
<table cellpadding="2" cellspacing="0" border="1" summary="User Grid" style="text-align: left">
<tr style="background-color: #ABC3CB;">
<th align="center">User Name</th>
<th align="center">Approved</th>
<th align="center"> </th>
<th align="center"> </th>
</tr>
<% foreach(MembershipUser membershipUser in ViewData.Model) { %>
<tr>
<td><%: membershipUser.UserName %></td>
<td align="center"><%: Html.CheckBox(" ", true, membershipUser.IsApproved ) %></td>
<td align="center">
<% using (Html.BeginForm( "DeleteItem", "Admin", new { id = membershipUser.UserName } )) { %>
<input type="image" src="<%: Url.Content( "~/Content/Images/Delete.jpg" ) %>" />
<% } %>
</td>
</tr>
<% } %>
</table>
The ManageUser view is displayed by the following code in the AdminController, thus
public ViewResult ManageUser( string searchType, string searchInput )
{
List<SelectListItem> searchOptionList = new List<SelectListItem>()
{
new SelectListItem() {Value="UserName", Text = "UserName"},
new SelectListItem() {Value="Email", Text = "Email"},
};
ViewData["searchOptionList"] = new SelectList( searchOptionList, "Value", "Text", searchType ?? "UserName" );
ViewData["searchInput"] = searchInput ?? string.Empty;
ViewData["searchType"] = searchType;
MembershipUserCollection viewData;
if (String.IsNullOrEmpty( searchInput ))
viewData = Membership.GetAllUsers();
else if (searchType == "Email")
viewData = Membership.FindUsersByEmail( searchInput );
else
viewData = Membership.FindUsersByName( searchInput );
ViewData["PageTitle"] = "Account Management";
return View( viewData );
}
When I display the page, and select the Delete choice, I expect it to run Admin/DeleteItem in the AdminController, thus
public RedirectToRouteResult DeleteItem( string id )
{
Membership.DeleteUser( id );
return RedirectToAction( "ManageUser" );
}
but instead, it is returning directly to the Admin/ManagerUser view, thus displaying my original set of records again.
I have obviously missed something but I cannot see what. Anybody help?
HTML <form> elements cannot be nested. Nesting them results in unexpected behavior which could vary between different browsers. Quote from the specification:
Every form must be enclosed within a
FORM element. There can be several
forms in a single document, but the
FORM element can't be nested.
So you might need to remove the outer form or find another way of organizing your markup.
How to handle dynamically generated form submit in asp.net mvc?
Form is dynamically created (number, order and type of elements are always different) and i have to handle it (store the data in the database) in the Controller of asp.net mvc (there is no viewstate). Type of input can be everything; hidden fields, radio buttons, check boxes, text inputs etc..
<% using (Html.BeginForm("AddAnswer","Research")){ %>
<%= Html.Hidden("page", ViewData["curentPage"]) %>
<% foreach (var item in Model){ %>
<span><%= Html.Encode(item.Text) %></span>
<%= Html.ActionLink("Edit", "Edit", new {id=item.QuestionID}) %>
|
<%= Html.ActionLink("Details", "Details", new { id=item.QuestionID })%>
<%switch (item.QuestionTipe.QuestionTipeID){
case 4:%>
<table>
<%foreach (var offeredAnswer in item.OfferedAnswer) {%>
<tr>
<td><%= Html.CheckBox("q" + item.QuestionID, false, new{ value = offeredAnswer.Number})%></td>
<td><%= offeredAnswer.Text%></td>
</tr>
<%}%>
</table>
<% break;
case 1:%>
<table>
<% foreach (var offeredAnswer in item.OfferedAnswer) {%>
<tr>
<td><%= Html.RadioButton("q" + item.QuestionID, false, new{ value = offeredAnswer.Number})%></td>
<td><%= offeredAnswer.Text%></td>
</tr>
<%}%>
</table>
<% break;
case 2:%>
<div style="width:220px; height:20px; padding-top:10px; padding-left:8px;">
<%= Html.TextBox("q" + item.QuestionID, null, new { style = "width:200px;"})%>
</div>
<% break;
case 3:%>
<div style="width:220px;height:20px; padding-top:10px;padding-left:8px;">
<div id="q<%= item.QuestionID %>" style="width:200px;" class="slider">
</div>
<%= Html.Hidden("q" + item.QuestionID, 0)%>
</div>
<% break;
}%>
<%}%>
<p>
<input type="submit" value="Sljedeća strana" />
</p>
<%}%>
In your action method, you can access FormCollection parameter, from there, you can access all your passed in values from your submit action.
public ActionResult YourActionMethod(FormCollection form)
{
}
In order to best help you decide how to process the form, it may be helpful to have some additional information.
Something is making the decision to generate this form, what is doing that? What is it basing its rendering on?
Are there known variations of the form that can be accounted for, or are the elements truly independent of each other?
Are each of the elements themselves known? If so, is it possible to give them a consistent id/name so that they may be recognized on the server-side?
When you speak of "handling" the submission, what is the end goal that you'd like to achieve? For example, are you parsing the form to store in a database?
foreach (var key in form.AllKeys) {
var answers = form.GetValues(key);
if (answers.Count() > 1){
foreach (var value in answers)
{
...
}
}
else
{
...
}
}
This is very simple. I'm checking if there is multiple values for some of the answers in the form.