У меня есть несколько флажков в представлении, и на true или false я запрашиваю базу данных, чтобы получить записи выбранной категории, а затем экспортирую эти записи в excel.
У меня есть несколько ActionMethods в моем проекте, и яЯ использую Tempdata для хранения выбранных категорий от пользователя.Как я должен передать эти категории в метод, где я экспортирую записи в Excel, поэтому я использую Tempdata .
Вот мое мнение.
@using (Html.BeginForm("SearchCustomReport", "PassengerInfo", FormMethod.Post))
{
<div class="form-group col-md-6 checkbox">
<label>@Html.CheckBoxFor(model => model.Business, new { @class = "big-checkbox" }) Business</label>
<div></div>
<div></div>
<label>@Html.CheckBoxFor(model => model.Gold, new { @class = "big-checkbox" }) Gold</label>
<div></div>
<div></div>
<label>@Html.CheckBoxFor(model => model.Platinium, new { @class = "big-checkbox" }) Platinium</label>
<div></div>
<div></div>
<label>@Html.CheckBoxFor(model => model.Guest, new { @class = "big-checkbox" }) Guest</label>
<div></div>
<div></div>
<label>@Html.CheckBoxFor(model => model.Paid, new { @class = "big-checkbox"}) Paid</label>
</div>
<div class="form-group col-sm-6">
<label>From</label>
@Html.EditorFor(model => model.Date1, new { htmlAttributes = new { @class = "form-control datepicker", id = "number", required = "required", placeholder = "From" } })
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label>To</label>
@Html.EditorFor(model => model.Date2, new { htmlAttributes = new { @class = "form-control datepicker", id = "number2", required = "required", placeholder = "To" } })
<div class="help-block with-errors"></div>
</div>
<div class="col-sm-12">
<input style="float: right ; background-color:white; color:#e60053 " type="Submit" class="btn" value="Generate Report" onmouseover=" this.style.backgroundColor = '#e60053', this.style.color = 'white' " onmouseout=" this.style.backgroundColor = 'white', this.style.color = '#e60053'">
</div>
}
Вот мой метод этого представления.
[HttpPost]
public ActionResult SearchCustomReport(CustomReport record)
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
if (record.Date1 == null || record.Date2 == null)
{
return View("invaliddatesinput");
}
if (record.Date1.Length< 10 ||record.Date2.Length > 10)
{
return View("invaliddatesinput");
}
if (record.Business == true)
{
TempData["Business"] = 1;
}
if (record.Gold == true)
{
TempData["Gold"] = 2;
}
if (record.Platinium == true)
{
TempData["Platinium"] = 3;
}
if (record.Guest == true)
{
TempData["Guests"] = 4;
}
if (record.Paid == true)
{
TempData["Paid"] = 5;
}
TempData["FromDate"] = record.Date1;
TempData["toDate"] = record.Date2;
return RedirectToAction("CustomReport");
}
Я держу выбранные категории и использую их в разных функциях.
public PassengerPaging GetCustomReport(int skipParam)
{
string frDate = TempData["FromDate"].ToString();
string toDate = TempData["toDate"].ToString();
int bus = Convert.ToInt32(TempData["Business"]);
int gold = Convert.ToInt32(TempData["Gold"]);
int plat = Convert.ToInt32(TempData["Platinium"]);
int guest = Convert.ToInt32(TempData["Guests"]);
int Paid = Convert.ToInt32(TempData["Paid"]);
TempData.Keep();
PassengerPaging psngr = new PassengerPaging();
psngr.Passengers = repository.GetCustomReport(bus, gold, plat, guest, Paid, frDate, toDate , skipParam).Select(x => new ViewModel.Passenger
{
ID = x.ID,
Name = x.Name,
FlightNo = FlightRepos.SelectByID(x.FlightId).Airline.AirlineCode + FlightRepos.SelectByID(x.FlightId).FlightNo,
Airline = FlightRepos.SelectByID(x.FlightId).Airline.Name,
SeatNo = x.SeatNo,
SequenceNo = x.SequenceNo,
Date = x.Date,
CheckinTime = x.CheckinTime,
CheckoutTime = x.CheckoutTime,
Category = categoryrepos.SelectByID(x.CategoryID).CategoryCode,
RefSeatNo = x.RefSeatNo,
isGuest = x.isGuest,
NoOfGuest = x.NoOfGuests,
Cash = x.Cash,
CreditCard = x.CreditCard,
EntryBy = x.EnterBy
}).ToList();
psngr.skip = skipParam;
if (psngr.Passengers.Count() > 0)
{
psngr.Count = repository.GetCustomReportForCount(bus, gold, plat, guest, Paid, frDate, toDate).Count() - skipParam;
}
return psngr;
}
У меня есть кнопка в представлении вышеметод, в котором пользователь может экспортировать данные в Excel.
<div class="col-md-3 col-sm-4 col-xs-12"> <a style="background-color:white" onmouseover=" this.style.backgroundColor = '#3597db', this.style.color = 'white'" onmouseout=" this.style.color='#3597db' ,this.style.backgroundColor = 'white'" class="btn " onclick="location.href='@Url.Action("ExportToExcelCustom", "PassengerInfo")'">Export Detail Data</a> </div>
Вот мой метод экспорта.
public IEnumerable<AllExcelRecords> GetListCustom()
{
int bus = Convert.ToInt32(TempData["Business"]);
int gold = Convert.ToInt32(TempData["Gold"]);
int plat = Convert.ToInt32(TempData["Platinium"]);
int guest = Convert.ToInt32(TempData["Guests"]);
int Paid = Convert.ToInt32(TempData["Paid"]);
string frDate = TempData["FromDate"].ToString();
string toDate = TempData["toDate"].ToString();
var result = repository.ExcelBydateCustom(bus, gold, plat, guest, Paid, frDate, toDate).Select(x => new ViewModel.AllExcelRecords
{
ID = x.ID,
Name = x.Name,
FlightNo = FlightRepos.SelectByID(x.FlightId).FlightNo,
Airline = FlightRepos.SelectByID(x.FlightId).Airline.Name,
SeatNo = x.SeatNo,
SequenceNo = x.SequenceNo,
Date = x.Date,
CheckinTime = x.CheckinTime,
CheckoutTime = x.CheckoutTime,
Remarks = x.Remarks,
EntryBy = x.EnterBy,
Category = categoryrepos.SelectByID(x.CategoryID).CategoryCode,
NoOfGuests = x.NoOfGuests,
RefSeatNo = x.RefSeatNo,
withGuests = x.isGuest,
Cash = x.Cash,
CreditCard = x.CreditCard
}).ToList();
return result;
}
public ActionResult ExportToExcelCustom()
{
if (!General.ValidateSession())
{
return RedirectToAction("Login", "User");
}
string fDate = TempData["FromDate"].ToString();
string tDate = TempData["toDate"].ToString();
var grdview = new GridView();
grdview.DataSource = this.GetListCustom();
grdview.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename= Customize Report " + fDate + " - " + tDate + ".xls ");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter strWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);
htmlWriter.Write("<table><tr><td colspan='13' align='center'><font size='45'>Customize Report</font></td></tr></table>");
grdview.RenderControl(htmlWriter);
Response.Output.Write(strWriter.ToString());
Response.Flush();
Response.End();
return RedirectToAction("DateRecords");
}
Проблема: она работает нормально, но есть проблема, с которой я сталкиваюсь.
Допустим, пользователь выбралбизнес и золотая категория и выполняя работу, он получил 12 записей этой конкретной категории, потому что в БД есть 12 записей из этих двух категорий.
Теперь пользователь вернулся и выбрал только категорию «Платиниум», а в БД 6 записей из этой единственнойкатегория, поэтому пользователь должен получить 6 записей, но он получает 12 + 6 = 18 записей.потому что в TempData золотая и бизнес категория присутствует.
, чтобы преодолеть это, я удалил эту строку Tempdata.keep, но после этого я не могу экспортировать данные в исключение, это выдает нулевое исключение.