Exporting data from table into excel with "xlxs"or "csv" extension - asp.net-mvc-4

I am using a export method in my controller to download data from table into excel file using this method:
here is my table in index file:
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Marks)
</th>
<th>
#Html.DisplayNameFor(model => model.Grade)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Marks)
</td>
<td>
#Html.DisplayFor(modelItem => item.Grade)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Details", "Details", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
</table>
and in my controller i have written this method which is triggered when u press the export button in index view:
public ActionResult ExportData()
{
GridView gv = new GridView();
gv.DataSource = db.Studentrecords.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("StudentDetails");
}
everything is working fine the table gets downloaded into the excel file easily but when i open the file it gives this error in the start of open file that:
The file format doesn't match.The file could be corrupted or unsafe.
The problem is causing mainly because file gets saved with xls format where as i want to save it in xlxs format how can that be possible?

To export the MVC view data into an Excel file, I am using the ClosedXml Library.
public ActionResult ExportToExcel()
{
var gv = new GridView();
gv.DataSource = this.GetEmployeeList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=DemoExcel.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
gv.RenderControl(objHtmlTextWriter);
Response.Output.Write(objStringWriter.ToString());
Response.Flush();
Response.End();
return View("Index");
}
Link to Complete Article Article Link

Related

How to make a viewModel to be Enumerable

I'm implementing asp.net core 3.1. I'm passing a viewmodel to the razor view which is in the following:
public class BuyRequestViewModel
{
public IEnumerable<BuyRequest> BuyRequestVM { get; set; }
public IEnumerable<string> PlatesVM { get; set; }
}
My problem is, as my viewmodel is not of type Ienumerable, I'm getting error in foreach in the razor view. The error is like the following:
ForEach statement can not operate on variables of type 'MyPanel.ViewModels.BuyRequestViewModel' because 'MyPanel.ViewModels.BuyRequestViewModel' does not contain a public instance definition for 'GetEnumerator'
And my razor view code is like below:
#model MyPanel.ViewModels.BuyRequestViewModel
<table id="myDummyTable" class="table m-table mytable table-striped table-bordered">
<thead>
<tr>
<th>
Region
</th>
<th>
Zone
<th>
MyPlate
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.BuyRequestVM.Select(x => x.Region))
</td>
<td>
#Html.DisplayFor(modelItem => item.BuyRequestVM.Select(x => x.Zone))
</td>
<td>
#Html.DisplayFor(modelItem => item.PlatesVM)
</td>
</tr>
}
</tbody>
</table>
And here below is the Index action in my controller:
public async Task<IActionResult> Index()
{
var bwrvm = new BuyRequestViewModel();
List<string> platesList = new List<string>();
var WasteAPIContext = _context.BuyRequest
.Include(b => b.UserWasteUnitNavigation).ToList();
bwrvm.BuyWasteRequestVM = WasteAPIContext;
var plateData = _context.Car.Select(x => x.Plate).ToList();
for (int i = 0; i < plateData.Count; i++)
{
//platesList.Add(plateData[i].ToString().Substring(2, 5));
string temp = getPlateCharacter(plateData[i].ToString().Substring(2, 3));
plateData[i].Remove(2, 3);
string totalPlate = plateData[i].Insert(2, temp);
platesList.Add(totalPlate);
}
bwrvm.PlatesVM = platesList;
return View(bwrvm);
}
I appreciate of any help.
#foreach (var item in Model)
should be
#foreach (var item in Model.BuyWasteRequestVM)
because Model == BuyRequestViewModel which contains 2 properties with lists.

Update Partial view MVC4

I have this controller:
public ActionResult PopulateTreeViewModel()
{
MainModelPopulate mainModelPopulate = new MainModelPopulate();
// populate model
return View(mainModelPopulate);
}
That has a view like this:
#model xxx.xxx.MainModelPopulate
<table>
#foreach (var item2 in Model.CountryList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item2.CountryName);
</td>
</tr>
foreach (var item3 in item2.BrandList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item3.BrandName);
</td>
</tr>
foreach (var item4 in item3.ProductList)
{
<tr>
<td>
#Html.ActionLink(item4.ProductName, "FunctionX", new { idLab = item3.BrandID, idDep = item4.ProductID });
</td>
</tr>
}
}
}
</table>
The FunctionX controller is like this :
public ActionResult FunctionX(int idBrand=1 , int idProd=1)
{
List<ListTypeModel> typeModelList = new List<ListTypeModel>();
// populate typeModelList
return PartialView(typeModelList);
}
}
with this partial view:
#model IEnumerable<TControl.Models.ListTypeModel>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
I want to add this partial view in my main view (PopulateTreeViewModel) and update the table with the relative type of product contained in Function X.
I tried also to substitute #Html.ActionLink with #Ajax.ActionLink and it performs the same way.
Have you tried #Html.RenderAction(item4.ProductName, "FunctionX", new { idLab = item3.BrandID, idDep = item4.ProductID });
There are other options too..! Pls refer http://www.dotnet-tricks.com/Tutorial/mvc/Q8V2130113-RenderPartial-vs-RenderAction-vs-Partial-vs-Action-in-MVC-Razor.html

Fetch id for viewpage

FIXED
what i want to do is a viewpage that contains accountslist by clicking on any of account name it should open selected accountid Payablerecords and Reciveablerecords. Note:Payables and Receivables are two Propertiest Taken From same DataModel tbl_Transaction(Which is collection).So can i get Id for collections?
I am getting the Selected AccountID records in Payable view but I cant get the same id related record in Reciveable view plz help me out.
Here is the code.
public class AccountsController : Controller
{
private AccountBs objBs;
public AccountsController()
{
objBs = new AccountBs();
}
// GET: Shinwari/Accounts
public ActionResult Index()
{
var accounts = objBs.GetALL();
return View(accounts);
}
<%=#model IEnumerable<BOL.tbl_Accounts>
#{
ViewBag.Title = "Index";
}
<h2>Accounts</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Contact)
</th>
<th>
#Html.DisplayNameFor(model => model.Discription)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink(item.Name, "Index", "AccountDetailPayable", new {accountid=item.AId },null)
#*#Html.DisplayFor(modelItem => item.Name)*#
</td>
<td>
#Html.DisplayFor(modelItem => item.Contact)
</td>
<td>
#Html.DisplayFor(modelItem => item.Discription)
</td>
}
</table>%>
ReciveableAndPayablecontroller
private TransictionBs objbs;
public Details()
{
objbs = new TransictionBs();
}
// GET: Shinwari/AccountDetails
[HttpGet]
public ActionResult Index(int accountid)
{
ADetailsVm v = new ADetailsVm();
//Load both the collection properties
v.Payables = objbs.GetALL().Where(p => p.AId == accountid && p.tbl_TransictionType.Type.Contains("Payable")).ToList();
v.Reciveables = objbs.GetALL().Where(r => r.AId==accountid && r.tbl_TransictionType.Type.Contains("Reciveable")).ToList();
return View(v);
Veiw
#model BOL1.ADetailsVm
#{
ViewBag.Title = "Index";
}
<h2>AccountDetails</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table id="Payables" class="table">
<tr>
<th>
Date
</th>
<th>
Discription
</th>
<th>
Amount
</th>
</tr>
#foreach (var item in Model.Payables)
{
<tr>
<td>
#item.Date
</td>
<td>
#item.TDiscription
</td>
<td>
#item.Amount
</td>
</tr>
}
</table>
**Note Payable and reciveable both views are identical **
TO have same table work like 2 different properties you need to create new model class, In my case it is as following..
public ADetailsVm
{
List<tbl_Transiction>Payables{get;set;}
List<tbl_Transiction>Reciveables{get;set;}
}
And then add the following class to DBContext Class ... it would be like
public DbSet<ADetailsVm>ADetailsVm{get;set;}
You have to create new class where you need to add two lists as following.
public NewClass
{
List<tbl_Transiction>Payables{get;set;}
List<tbl_Transiction>Reciveables{get;set;}
}
and Add the class to your DbContext Class as follows.
public DbSet<NewClass>PayablesAndReceiveables{get;set;}
And loop your newly created lists objects in View where you need them.

Insert Partial View to a another Partial View

This is the main view Dept_Manager_Approval.cshtml where I have put a modal to show data.
<td>
<i title="View Details">
#Ajax.ActionLink(" ", "ViewAccessStatus", new { id = item.request_access_id },
new AjaxOptions
{
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "edit-div",
}, new { #class = "fa fa-eye btn btn-success approveModal sample" })</i>
</td>
In this partial view which just a modal, ViewAccessStatus.cshtml , I have inserted in here another partial view.
<div>
<h2><span class ="label label-success">Request Creator</span> </h2>
#if (Model.carf_type == "BATCH CARF")
{
#Html.Partial("Batch_Requestor1", new {id= Model.carf_id })
}else{
<h4><span class ="label label-success">#Html.DisplayFor(model=>model.created_by)</span></h4>
}
</div>
COntroller:
public ActionResult Batch_Requestor1(int id = 0)
{
var data = db.Batch_CARF.Where(x => x.carf_id == id && x.active_flag == true).ToList();
return PartialView(data);
}
Batch_Requestor1.cshtml
#model IEnumerable<PETC_CARF.Models.Batch_CARF>
#{
ViewBag.Title = "All Requestors";
}
<br/><br/>
<table class="table table-hover">
<tr class="success">
<th>
#Html.DisplayName("Full Name")
</th>
<th>
#Html.DisplayName("Email Add")
</th>
<th>
#Html.DisplayName("User ID")
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.fname) - #Html.DisplayFor(modelItem => item.lname)
</td>
<td>
#Html.DisplayFor(modelItem => item.email_add)
</td>
<td>
#Html.DisplayFor(modelItem => item.user_id)
</td>
</tr>
}
</table>
When I run this, I've got this error
The model item passed into the dictionary is of type '<>f__AnonymousType01[System.Int32]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[PETC_CARF.Models.Batch_CARF]'.
Any ideas how will I insert another partial view?
#Html.Partial() renders a partial view. It does not call an action method that in turn renders the partial. In your case
#Html.Partial("Batch_Requestor1", new {id= Model.carf_id })
is rendering a partial view named Batch_Requestor1.cshtml and passing it a model defined by new {id= Model.carf_id } (and anonymous object) but that view expects a model which is IEnumerable<PETC_CARF.Models.Batch_CARF>.
Instead, you need to use
#Html.Action("Batch_Requestor1", new {id= Model.carf_id })
which calls the method public ActionResult Batch_Requestor1(int id = 0) and passes it the value of Model.carf_id, which will in turn render the partial view.

System.InvalidOperationException: The partial view '_Reservaion' was not found or no view engine supports the searched locations

In my MVC 4 App i'm trying to use an Ajax form to implement a search to my 'Reservation' repository.
My View: (Views/Reservation/Index):
#model IEnumerable<RentalsForceProject.Models.Reservation>
#{
ViewBag.Title = "Reservations Center";
ViewBag.current = "Reservation";
}
#section featured {
#Html.Partial("_Navigator")
}
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ReservaionList"
}))
{
<input type="search" name="searchTerm" />
<input type="submit" name="Search By Contact" />
}
<p>
<input type="button" value="Create New" class="greenButton" style="margin-top:20px;" onclick="location.href='#Url.Action("Create", "Reservation")'"/>
</p>
#Html.Partial("_Reservation", Model)
My Partial view (Views/Reservation/_Reservation):
#model IEnumerable<RentalsForceProject.Models.Reservation>
<div id="ReservaionList" class="table-responsive">
<table class="table table-ordered">
<tr>
<th>
Reservation
</th>
<th>
Name
</th>
<th>
Dates
</th>
<th>
# Nights
</th>
<th>
Status
</th>
<th></th>
</tr>
#foreach (var res in Model)
{
<tr>
<td>
#res.ID
</td>
<td>
#if (res.Contact != null) {
#Html.ActionLink(res.Contact.FirstName + " " + res.Contact.LastName, "Details", "Contact", new { id=res.Contact.ID }, null)
//#res.Contact.LastName #: #res.Contact.LastName
}
</td>
<td>
#if (res.Request != null) {
#res.Request.StartDate #:- #res.Request.EndDate
}
</td>
<td>
#res.calculteNights()
</td>
<td>
#if (res.Status != null) {
#res.Status
}
</td>
<td>#Ajax.ActionLink("Edit", "Edit", "Reservation", new { id = res.ID }, new AjaxOptions() { HttpMethod = "Post" }) | #Ajax.ActionLink("View", "Details", new { id = res.ID }, new AjaxOptions() { HttpMethod = "Post" }) | #Ajax.ActionLink("Delete", "Delete", new { id = res.ID }, new AjaxOptions() { HttpMethod = "Post" })</td>
</tr>
}
</table>
</div>
My Index ActionResult:
public ActionResult Index(string searchTerm = null)
{
if (unitOfWork.currentClient == null)
{
return RedirectToAction("LogOn", "Account");
}
else
{
ViewBag.currentClient = unitOfWork.currentClient;
if (Request.IsAjaxRequest() && searchTerm != null)
return PartialView("_Reservaion", unitOfWork.currentClient.getAllReservationsBySearchTerm(searchTerm));
return View(unitOfWork.currentClient.getAllReservations());
}
}
When i lunch the 'search' button i can see it creates to nesessary model to the partial view, but nothing happens in the view.
I tried to use Chrome developers tools -> F12 - Network tab, and found out this exception:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The partial view '_Reservaion' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Reservation/_Reservaion.aspx
~/Views/Reservation/_Reservaion.ascx
~/Views/Shared/_Reservaion.aspx
~/Views/Shared/_Reservaion.ascx
~/Views/Reservation/_Reservaion.cshtml
~/Views/Reservation/_Reservaion.vbhtml
~/Views/Shared/_Reservaion.cshtml
~/Views/Shared/_Reservaion.vbhtml
Any Idea ?