how to pagination razor page? - asp.net

i have a table for saving some ids for send request to web service and save my data to view model and show data in view page with IEnumerable viewmodel.Now i want to have a pagination at the end of my page because i have more than 100 product in my archive page.Now how can i have Pagination for this page??
//CONTROLLER
public ActionResult Archive()
{
var selectspecial = db.ProviderSelections.Where(a =>
a.SpecialSuggestion == true && a.IsActive ==
true).OrderByDescending(a => a.CreateDate).Select(a =>
a.ID).ToList();
var lastitem = selectspecial.Last();
List<string> lst = new List<string>();
for (int i = 0; i < selectspecial.Count; i++)
{
var selectid = selectspecial[i];
lst.Add(selectid.ToString());
}
StringBuilder itemlist = new StringBuilder();
foreach (var item in lst)
{
itemlist.Append(item).Append(",");
}
string id = itemlist.ToString() + lastitem;
WebClient webclient = new WebClient();
webclient.Headers[HttpRequestHeader.ContentType] =
"application/json;charset=utf-8";
string url = "MYWEBSERVICEURL?pids=" + id;
webclient.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("USERNAME:PASSWORD"));
webclient.Headers.Add("Request-type", "REQUESTTYPE");
string result = webclient.DownloadString(url);
JObject jObject = JObject.Parse(result);
JToken jUser = jObject["X"];
List<BriefDetailsViewModel> briefdetails = new
List<BriefDetailsViewModel>();
foreach (var item in jUser)
{
BriefDetailsViewModel brief = new BriefDetailsViewModel();
brief.address = (string)item["address"];
//OTHER LINES ARE LIKE ABOVE LINE
briefdetails.Add(brief);
}
return View(briefdetails);
}
//Archive.cshtml
#model IEnumerable<ROOT.BriefDetailsViewModel>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
#foreach (var item in Model)
{
<div class="col-lg-9 col-md-9 col-sm-8 col-xs-8">
<div class="text TextBox">
#item.description
</div>
</div>
//More Data like this....
}
//PAGINATION BOX
</div>

The best practice by adding pagination feature to your web service to be like this :
string url = "MYWEBSERVICEURL?pids=" + id + "&pageId="+pageId;
Also use page size variable, then you can page your data using LINQ :
example :
int numberOfObjectsPerPage = 10;
var queryResultPage = dataContext.Employees.OrderBy(a=>a.ID)
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage).ToList();
If you cannot update your web service, or you are using external web service you can read the data then page it before return your view :
briefdetails = briefdetails
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage);
return View(briefdetails);
Also in your html you can render something for paging below your table :
//You called it PAGINATION BOX
for(int i=1,i<pageNumber;i++)
{
<a href="#Url.Action("YOUR_ACTION",new {pageId = i})">#i<a/>
}

Related

Extract Data from Excel File to use it in an ASP.net core application

I am developing an application where I have to get the data from an Excel sheet and use it in the application, but I am having trouble accessing the data. Should I use Entity Framework and move the Data to a database or do I just import the data from Excel and use it?
Not sure what trouble you are meeting to access the data. But here is a sample about importing Excel data to Asp.net core application, you could refer to it.
In this sample, it will upload the excel file to the wwwroot folder using JavaScript first, then, using the DotNetCore.NPOI package (open source, you could install it via Nuget) to extract the data from excel. Details steps as below:
Suppose there have a testdata.xlsx file, the content as below:
Code in the controller:
private readonly IWebHostEnvironment _hostEnvironment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment)
{
_logger = logger;
_hostEnvironment = environment;
}
public IActionResult Upload()
{
return View();
}
[HttpPost]
public IActionResult Import()
{
IFormFile file = Request.Form.Files[0];
string folderName = "UploadExcel";
string webRootPath = _hostEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
StringBuilder sb = new StringBuilder();
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
ISheet sheet;
string fullPath = Path.Combine(newPath, file.FileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
stream.Position = 0;
if (sFileExtension == ".xls")
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
else
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
IRow headerRow = sheet.GetRow(0); //Get Header Row
int cellCount = headerRow.LastCellNum;
sb.Append("<table class='table table-bordered'><tr>");
for (int j = 0; j < cellCount; j++)
{
NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
sb.Append("<th>" + cell.ToString() + "</th>");
}
sb.Append("</tr>");
sb.AppendLine("<tr>");
var emplist = new List<EmployeeViewModel>();
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
}
sb.AppendLine("</tr>");
EmployeeViewModel emp = new EmployeeViewModel() {
EmployeeID = Convert.ToInt32(row.Cells[0].ToString()),
EmployeeName = row.Cells[1].ToString(),
Age = Convert.ToInt32(row.Cells[2].ToString()),
Sex = row.Cells[3].ToString(),
Designation = row.Cells[4].ToString()
};
emplist.Add(emp);
}
var result = emplist;
sb.Append("</table>");
}
}
return this.Content(sb.ToString());
//return View("Upload");
}
Code in the Upload view:
<form asp-controller="Home" asp-action="Export">
<div class="container">
<div class="row">
<div class="col-md-4">
<input type="file" id="fileupload" name="files" class="form-control" />
</div>
<div class="col-md-3">
<input type="button" name="Upload" value="Upload" id="btnupload" class="btn btn-primary" />
Download
</div>
<div class="col-md-5">
<input type="submit" name="Export" value="Create and Export" id="btnExport"
class="btn btn-primary" asp-action="Export" />
</div>
</div>
<div class="clearfix"> </div>
<div class="row">
<div id="divPrint"></div>
</div>
</div>
</form>
And the Java Script code:
<script type="text/javascript">
$(function () {
$('#btnupload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) == -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fileupload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/Home/Import",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
$('#divPrint').html(response);
}
},
error: function (e) {
$('#divPrint').html(e.responseText);
}
});
})
$('#btnExport').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file then Import");
return false;
}
});
});
</script>
The result like this:
You could also create a Employee model to store the data:
public class EmployeeViewModel
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public string Designation { get; set; }
}
Then, when loop through the excel rows, use the following code to get the Employee List:
var emplist = new List<EmployeeViewModel>();
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
}
sb.AppendLine("</tr>");
EmployeeViewModel emp = new EmployeeViewModel() {
EmployeeID = Convert.ToInt32(row.Cells[0].ToString()),
EmployeeName = row.Cells[1].ToString(),
Age = Convert.ToInt32(row.Cells[2].ToString()),
Sex = row.Cells[3].ToString(),
Designation = row.Cells[4].ToString()
};
emplist.Add(emp);
}
If the above sample doesn't achieve your requirement, please explain more details about what trouble are you having and what library you are using to upload the excel.
Reference:
Import and Export Excel file using NPOI
Import (Insert) Excel file data into Database ASP.Net Core MVC (using OLEDB library)

How can i get Kendo Grid DataItem

How can i get the selected row KendoGrid Data Item?
I research a lot online and I came across this post http://dojo.telerik.com/egUpI which does exactly what i am looking for i would like implement the same.
I have the following code to populate grid in asp.net view. I need your help when row selected populate a elements.
Here is my Grid View:
<h1> Contacts</h1>
#{
var gridColumnSettings = new List<GridColumnSettings>
{
new GridColumnSettings
{
Member = nameof(Contact.Name),
MemberType = typeof(string)
},
new GridColumnSettings
{
Member = nameof(Contact.PhoneNumber),
MemberType = typeof(string)
}
};
var gridViewModel = new GridViewModel
{
Name = "ContactGrid", // Grid Name
Columns = gridColumnSettings,
AutoBind = true,
DataSourceSettings = new GridDataSourceSettings
{
ReadDataSource = new DataSourceSetting()
{
ActionName = "Contact",
ControllerName = "Contact",
HttpVerb = HttpVerbs.Get,
}
},
SelectionSettings = new GridSelectionSettings
{
IsSelectable = true, // To make grid selectable
GridSelectionMode = 0,
GridSelectionType = 0
},
}
};
}
Here is my Form on the same Page to display the selected grid row information
<form>
<h3>Name</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control " id="Name">
</div>
<h3>Phone</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control" id="Phone">
</div>
</form>
I tried this Jquery, but not working
<script>
function fillForm() {
$("#ContactGrid").kendoGrid({
change: function (e) {
var dataItem = this.dataItem(this.select());
fillForm(dataItem);
}
});
}
// Fill Form based on the selected row
var fillForm = function(dataItem) {
var columns = $("#ContactGrid").data("kendoGrid").options.columns;
var form = $("form");
for (var i = 0; i < columns.length; i++) {
var field = columns[i].field;
form.find("#" + field).val(dataItem[field]);
}
}
</script>

How insert multiple string values on single node in builtin LinkedList type in mvc asp.net

I'm newbie in this field.
I have a table called comment. And i want to get multiple column data and multiple rows. Like I row-1 has two columns.
Can I use Linked List to pass data from controller to view?If so how should I do that. If not than how should I pass data from controller to view. I know ViewBag, Session etc. But they are no help to me.
When I run this code it gives me following exception
"Object reference not set to an instance of an object".
How should I code in controller and view too. Will there be a connection of this with model too?
Please if you have some source link about How to use LinkList in MVC4 Asp.Net, please do share.
Any kind of help will be much appreciated.
Controller
***>
Comment CommentObj = new Comment();
try
{
var query = from comment in db.Comments
from TeachOb in db.TeacherAccounts
from StdOb in db.StudentAccounts
select new
{
CommentBy = comment.UserID,
CommentOn = comment.PostID,
CommentContent = comment.CommentContent,
TeacherName = TeachOb.TeacherName,
StudentName = StdOb.UserName
};
LinkedList<string> getData = new LinkedList<string>();
LinkedListNode<string> Node = new LinkedListNode<string>("");
foreach (var Info in query)
{
if (Info.CommentOn == PostID && Info.CommentBy == Loggedinuser)
{
string commentBy = Info.CommentBy.ToString();
string commentOn = Info.CommentOn.ToString();
string commentContent = Info.CommentContent.ToString();
string teacherName = Info.TeacherName.ToString();
Node.Value = commentBy;
Node.Value = commentOn;
getData.AddFirst(Node);
}
Session["list"] = getData;
}
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
Blockquote
This my View
Blockquote
#foreach (var std in Session["list"] as LinkedList<string>)
{
<li>
<a href="#">
#std.ToString();
</a>
<br /><br />
</li>
}
Try with this may be this will help.
foreach (var Info in query)
{
if (Info.CommentOn == PostID && Info.CommentBy == Loggedinuser)
{
string commentBy = Info.CommentBy.ToString();
string commentOn = Info.CommentOn.ToString();
string commentContent = Info.CommentContent.ToString();
string teacherName = Info.TeacherName.ToString();
Node.Value = commentBy;
Node.Value = commentOn;
getData.AddFirst(Node);
}
}
if(getData!= null)
{
ViewBag.ListData = getData;
}
View Blog
#foreach (var std in ViewBag.ListData)
{
<li>
<a href="#">
#std.ToString();
</a>
<br /><br />
</li>
}

ASP.NET MVC 3 Charting and HTTPPOST

Working in Asp.Net MVC 3.
Controller Code:
[HttpPost]
public ActionResult MyChart(string sDate)
{
/*Call Entity Database*/
Contact_Center_DashboardEntities3 db = new Contact_Center_DashboardEntities3();
var results01 = db.sp_Report_Hybrid_Metrics("9 September", sDate, "Auto", "R2/R8", "Claims", "Claims", "R02_R08.AUTO.CLM.FMN.Q").ToList();
var chart = new Chart();
chart.Width = 1000;
chart.Height = 200;
var area = new ChartArea();
// configure your chart area (dimensions, etc) here.
chart.ChartAreas.Add(area);
area.AxisX.MajorGrid.Enabled = false;
area.AxisY.MajorGrid.Enabled = false;
area.AxisY2.MajorGrid.Enabled = false;
area.AxisY2.LabelStyle.Format = "0%";
// create and customize your data series.
var series = new Series();
foreach (var item in results01)
{
series.Points.AddXY(item.Date, item.Volume);
}
series.Font = new Font("Segoe UI", 8.0f, FontStyle.Bold);
series.ChartType = SeriesChartType.Column;
series.YAxisType = AxisType.Primary;
// create and customize your data series.
var seriesSecondary = new Series();
foreach (var item in results01)
{
seriesSecondary.Points.AddXY(item.Date, item.XferPer);
}
seriesSecondary.Font = new Font("Segoe UI", 8.0f, FontStyle.Bold);
seriesSecondary.ChartType = SeriesChartType.Line;
seriesSecondary.YAxisType = AxisType.Secondary;
seriesSecondary.LabelFormat = "0%";
seriesSecondary.IsValueShownAsLabel = true;
chart.Series.Add(series);
chart.Series.Add(seriesSecondary);
var returnStream = new MemoryStream();
chart.ImageType = ChartImageType.Png;
chart.SaveImage(returnStream);
returnStream.Position = 0;
return new FileStreamResult(returnStream, "image/png");
}
Tables View Code:
#using (Html.BeginForm("MyChart", "Home", FormMethod.Post))
{
<fieldset>
<div class="editor-field">
<input type="submit" value="09/06/2014" name = "sDate"/>
</div>
</fieldset>
}
When the user clicks the Submit button, the value passes to the "MyChart" ActionResult correctly, but then takes me to the MyChart view. What I need it to do is pass the value through, stay on the Tables View, and refresh the chart.
You could try something like this:
#using (Ajax.BeginForm("MyChart", "Home", new AjaxOptions{HttpMethod= "Post", UpdateTargetId = "chartContainer", InsertionMode = InsertionMode.Replace}))
{
<fieldset>
<div class="editor-field">
<input type="submit" value="09/06/2014" name = "sDate"/>
</div>
</fieldset>
}
<div id="chartContainer">
</div>
The request is done by ajax and inserts the response of the request into the element addressed by updatetargetid. If the submit button should be deleted after clicking it once, place the form inside the div. Otherwise the chart would be refreshed overtime you press the submit-button.

Setting A Variable With #Html.TextBox MVC3 ASP.Net

I'm working on a MVC3 ASP.Net application. I'm trying to figure out how to set the Quantity variable so when I pass it through to the controller with Html.ActionLink it has the correct number. Here's the view's code
#model IEnumerable<GreatVideosTrainingApplication.Models.Candy>
#{
ViewBag.Title = "Great Videos";
List<GreatVideosTrainingApplication.Models.Candy> candies = new List<GreatVideosTrainingApplication.Models.Candy>();
foreach (var candy in Model)
{
candies.Add(candy);
}
var grid = new WebGrid(candies);
var Quantity = 0;
}
<p>Welcome To Great Videos! The best source for your favorite DVDs and Blu-Rays</p>
<img src ="/Content/Images/dvd50.jpg" />
<p></p>
<img src="/Content/Images/bluray.jpg" />
<form method="post" action="/ShoppingCart/AddToCandyCart/"+item.CandyID >
#grid.GetHtml(#columns: grid.Columns(
grid.Column("Name"),
grid.Column("Price"),
grid.Column("Quantity", format: (item) => #Html.TextBox("Quantity", #Quantity)),
grid.Column("AddToCart", format: (item) => Html.ActionLink("Add To Cart", "AddToCandyCart", "ShoppingCart", new { id = item.CandyID, quantity = #Quantity }, ""))
)
)
</form>
I'm trying to set the value for the quantity with the Html.TextBox but it's not working. Keep in mind here I don't know javascript, and I'm extremely new to MVC3. Any and all help is greatly appreciated though.
public ActionResult AddToCandyCart(int id, FormCollection values)
{
// Add it to the shopping cart
var quantity = values["Quantity"];
var cart = ShoppingCart.GetCart(this.HttpContext);
// Retrieve the video from the database
var addedCandy = storeDB.Candies.Single(Candy => Candy.CandyID == id);
cart.AddToCandyCart(addedCandy, int.Parse(quantity));
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
The following code worked for me when including a textbox. I had trouble with the html helpers so I just wrote the code for the input box directly. I hope this helps.
grid.Column("Quantity", format: #<text><input name="Quantity" type="text" value="#item.Quantity"</text>))
Figured out the problem from mixing a variety of sources. Wanted to thank everyone. Here's the view.
#model IEnumerable<GreatVideosTrainingApplication.Models.Candy>
#{
ViewBag.Title = "Great Videos";
List<GreatVideosTrainingApplication.Models.Candy> candies = new List<GreatVideosTrainingApplication.Models.Candy>();
foreach (var candy in Model)
{
candies.Add(candy);
}
var grid = new WebGrid(candies);
var Quantity = 0;
}
<p>Welcome To Great Videos! The best source for your favorite DVDs and Blu-Rays</p>
<img src ="/Content/Images/dvd50.jpg" />
<p></p>
<img src="/Content/Images/bluray.jpg" />
<form method="post" action="../ShoppingCart/AddToCandyCart/" >
#using (Html.BeginForm()) {
#grid.GetHtml(#columns: grid.Columns(
grid.Column("Name"),
grid.Column("Price"),
grid.Column("Quantity", format: #<text><input name="Quantity" type="text" value="#Quantity"</text>),
grid.Column("AddToCart", format: #<text><input type="submit" value="Add To Cart" name="submit" /></text>)
)
)
}
</form>
Here's the Action Controller
[HttpPost]
public ActionResult AddToCandyCart(FormCollection values)
{
int id = 1;
string[] quantities = values["Quantity"].Split(',');
foreach (var item in quantities)
{
try
{
int quantity = int.Parse(item);
if (quantity >= 1)
{
// Add the candy to the shopping cart
var addedCandy = storeDB.Candies.Single(Candy => Candy.CandyID == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCandyCart(addedCandy, int.Parse(item));
}
}
catch (Exception e)
{
return View("Failed");
}
id++;
}
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}

Resources