Having trouble with paging in asp repeater - c#

I have this aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SearchCustomer.aspx.cs" Inherits="WebApplication1.eyeofheaven.SearchCustomer" %>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width = device-width, initial-scale = 1.0, minimum-scale = 1.0, maximum-scale = 1.0, user-scalable = no" />
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="StyleSheets/SearchCustomerStyle.css">
<link rel="stylesheet" href="Plugins/bootstrap-3.3.4-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Pagination Script -->
<!--Customer Script-->
<script src="JavaScripts/SearchCustomerJavascript.js"></script>
<title>Search Customer</title>
</head>
<body>
<div class="container">
<div class="row">
<form id="Form1" class="form1" runat="server">
<div class="row">
<div class="twelve columns">
<!-- Header-->
<div class="container">
<nav role="navigation" class="navbar navbar-inverse navbar-fixed-top">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collection of nav links, forms, and other content for toggling -->
<div id="navbarCollapse" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle active" href="#">Search<b class="caret"></b></a>
<ul role="menu" class="dropdown-menu">
<li>Search Form(Customer)</li>
<li>Search Form(Vehicle)</li>
</ul>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
<!-- Search form customer-->
<div id="searchcustomer" class="page-header">
<h3><span class="glyphicon glyphicon-th-large"></span>Search Customer</h3>
</div>
<div class="row">
<div class="col-md-4">
<input type="text" runat="server" id="search" size="20" class="form-control" placeholder="Customer ID">
</div>
<div class="col-md-4">
<select class="form-control" runat="server" id="Country">
<option value="select" selected disabled>Search by Country</option>
<option value="A:C ESTUDIO">A:C ESTUDIO</option>
<option value="Aaron McEwen-194712">Aaron McEwen-194712</option>
<option value="Accra">Accra</option>
<option value="Adoany">Adoany</option>
<option value="Aduanas">Aduanas</option>
<option value="Alex Sanchez-259029">Alex Sanchez-259029</option>
<option value="ALG Consulting-288078">ALG Consulting-288078</option>
<option value="Algeria">Algeria</option>
<option value="Algimantas Ramaskevicius">Algimantas Ramaskevicius</option>
<option value="Allan Demeritte-233953">Allan Demeritte-233953</option>
<option value="Althea Gibson-223990">Althea Gibson-223990</option>
<option value="Alvaro Delgado-279974">Alvaro Delgado-279974</option>
<option value="Amber Williamsen-212332">Amber Williamsen-212332</option>
<option value="Amos Peters-217784">Amos Peters-217784</option>
<option value="andersongordon-234453">andersongordon-234453</option>
<option value="Andrey Bolshakov-189544">Andrey Bolshakov-189544</option>
<option value="Angela green-220269">Angela green-220269</option>
<option value="ANGELMILLER-179184">ANGELMILLER-179184</option>
<option value="Angola">Angola</option>
<option value="Anguilla">Anguilla</option>
<option value="Anthony Knight-235064">Anthony Knight-235064</option>
<option value="Antigua and Barbuda">Antigua and Barbuda</option>
</select>
</div>
<div class="col-md-4">
<select class="form-control" runat="server" id="Currency">
<option value="selected" selected disabled>Search by Currency</option>
<option value="AUD">AUD (Australian Dollar)</option>
<option value="EUR">EUR (Euro)</option>
<option value="GBP">GBP (United Kingdom Pounds)</option>
<option value="JPY">JPY (Japan Yen)</option>
<option value="NZD">NZD (New Zealand Dollar)</option>
<option value="USD">USD (United States Dollar)</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button type="button" runat="server" onserverclick="Button1_Click" id="searchinfo" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>Search Info</button>
<button type="button" runat="server" onserverclick="Button2_Click" id="Button2" class="btn btn-danger"><span class="glyphicon glyphicon-repeat"></span>Reset</button>
</div>
</div>
<hr style="border-top: dotted 1px;" />
<!-- Information Table-->
<div class="row">
<asp:Repeater runat="server" ID="repeater">
<ItemTemplate>
<div class="col-md-8">
<div id="panelmain" class="panel panel-default">
<div id="panel-heading" class="panel-heading">
<h3 id="name" align="center" class="panel-title"><%# String.Format("{0} {1}", DataBinder.Eval(Container.DataItem, "Firstname").ToString(), DataBinder.Eval(Container.DataItem, "Lastname").ToString()) %></h3>
</div>
<div id="panelbody" class="panel-body">
<ul class="list-unstyled">
<li>
<span class="spanlist">IDCustomer : </span><%# DataBinder.Eval(Container.DataItem, "IDCustomer").ToString() %>
</li>
<li>
<span class="spanlist">IDAccountManager : </span><%# DataBinder.Eval(Container.DataItem, "IDAccountManager").ToString() %>
</li>
<li>
<span class="spanlist">IDBillingAddress : </span><%# DataBinder.Eval(Container.DataItem, "IDBillingAddress").ToString() %>
</li>
<li>
<span class="spanlist">IDCountry : </span><%# DataBinder.Eval(Container.DataItem, "IDCountry").ToString() %>
</li>
<li>
<span class="spanlist">IDCredit : </span><%# DataBinder.Eval(Container.DataItem, "IDCredit").ToString() %>
</li>
<li>
<span class="spanlist">IDFrequency : </span><%# DataBinder.Eval(Container.DataItem, "IDFrequency").ToString() %>
</li>
<li>
<span class="spanlist">IDOwner : </span><%# DataBinder.Eval(Container.DataItem, "IDOwner").ToString() %>
</li>
<li>
<span class="spanlist">IDPort : </span><%# DataBinder.Eval(Container.DataItem, "IDPort").ToString() %>
</li>
<li>
<span class="spanlist">IDSite : </span><%# DataBinder.Eval(Container.DataItem, "IDSite").ToString() %>
</li>
<li>
<span class="spanlist">IDRecipient : </span><%# DataBinder.Eval(Container.DataItem, "IDRecipient").ToString() %>
</li>
<li>
<span class="spanlist">AccessType : </span><%# DataBinder.Eval(Container.DataItem, "AccessType").ToString() %>
</li>
<li>
<span class="spanlist">Active : </span><%# DataBinder.Eval(Container.DataItem, "Active").ToString() %>
</li>
</ul>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div>
<asp:LinkButton ID="linkPrevious" runat="server" NavigateUrl="~/SearchCustomer.aspx" Font-Bold="true" OnClick="linkPrevious_Click">Prev Page</asp:LinkButton>
<asp:LinkButton ID="linkNext" runat="server" NavigateUrl="~/SearchCustomer.aspx" Font-Bold="true" OnClick="linkNext_Click">Next Page</asp:LinkButton>
</div>
</form>
</body>
</html>
and its aspx code behind:
using MSSQLConnector;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1.eyeofheaven
{
public partial class SearchCustomer : System.Web.UI.Page
{
public static string query = null;
private int cnt;
private DataSet selectedData;
private DataTable dt;
private MSConnector connector = new MSConnector();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Function for BindRepeater
BindRepeater();
}
protected void Button2_Click(object sender, EventArgs e)
{
this.repeater.Visible = false;
this.search.Value = "";
this.Country.Value = "select";
this.Currency.Value = "selected";
}
//This property will contain the current page number
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set { ViewState["PageNumber"] = value; }
}
//Asp:ListView
private void BindRepeater()
{
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=xbetasql,52292;UID=username;Password=secret;DATABASE=ATDBSQL;";
//Get the values from id's
string customer = (this.search.Value);
string country = (this.Country.Value);
string idcurrency = (this.Currency.Value);
//Conditions for query
if (country != "select")
{
if (idcurrency != "selected")
{
query = "select * from customer where country = '" + country + "' and idcurrency = '" + idcurrency + "'";
}
else
{
query = "select * from customer where country = '" + country + "'";
}
}
else if (idcurrency != "selected")
{
query = "select * from customer where idcurrency = '" + idcurrency + "'";
}
else if ((this.search.Value) == customer)
{
query = "select * from customer where idcustomer = '" + customer + "'";
}
else if (customer == "")
{
Response.Write("<script>alert('No Id Inputted, Data Not Found.')</script>");
}
//DataSet and DataTable (get the data and display it into asp:repeater
selectedData = connector.ExecuteQuery(query);
dt = selectedData.Tables[0];
//Set PageData Settings
PagedDataSource pagedData = new PagedDataSource();
pagedData.DataSource = dt.DefaultView;
pagedData.AllowPaging = true;
pagedData.PageSize = 3;
pagedData.CurrentPageIndex = PageNumber;
int vcnt = cnt / pagedData.PageSize;
if (PageNumber < 1)
{
linkPrevious.Visible = false;
}
else if (PageNumber > 0)
{
linkPrevious.Visible = true;
}
if (PageNumber == vcnt)
{
linkNext.Visible = false;
}
else if(PageNumber < vcnt)
{
linkNext.Visible = true;
}
//Binding the repeater
repeater.Visible = true;
repeater.DataSource = pagedData;
repeater.DataBind();
//Binding the repeater
}
protected void linkNext_Click(object sender, EventArgs e)
{
PageNumber += 1;
BindRepeater();
}
protected void linkPrevious_Click(object sender, EventArgs e)
{
PageNumber -= 1;
BindRepeater();
}
}
}
My asp:LinkButton, does not work for paging in my repeater when I first open my web page the asp:linkbutton is there, but when searched and display all the data from my page the linkbutton is gone although it display data that I searched for. But the problem is pagination doesn't seem to work. What seems to be the problem for my code? Here's the link as a reference for my code.
I'm new to c# programming(webform) and I have few knowledge about pagination in c#.

It's because of
int vcnt = cnt / pagedData.PageSize;
'cnt' you haven't set, So its always zero that's why 'vcnt' will zero.
that's why your link will visible false always after you search things.
So Solution is
int vcnt = dt.DefaultView.Count / pagedData.PageSize;
Hope this will solve your problem
Happy Coding :)

I got it right :)
here's the code for pagination:
using MSSQLConnector;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1.eyeofheaven
{
public partial class SearchCustomer : System.Web.UI.Page
{
public static string query = null;
private int cnt;
private DataSet selectedData;
private DataTable dt;
private MSConnector connector = new MSConnector();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Function for BindRepeater
BindRepeater();
}
protected void Button2_Click(object sender, EventArgs e)
{
this.repeater.Visible = false;
this.linkPrevious.Visible = false;
this.linkNext.Visible = false;
this.search.Value = "";
this.Country.Value = "select";
this.Currency.Value = "selected";
}
//This property will contain the current page number
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set { ViewState["PageNumber"] = value; }
}
//Asp:ListView
private void BindRepeater()
{
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=xbetasql,52292;UID=username;Password=secret;DATABASE=ATDBSQL;";
//Get the values from id's
string customer = (this.search.Value);
string country = (this.Country.Value);
string idcurrency = (this.Currency.Value);
//Conditions for query
if (customer != "")
{
query = "select * from customer where idcustomer = '" + customer + "'";
}
else if (country != "select")
{
if (idcurrency != "selected")
{
query = "select * from customer where country = '" + country + "' and idcurrency = '" + idcurrency + "'";
}
else
{
query = "select * from customer where country = '" + country + "'";
}
}
else if (idcurrency != "selected")
{
query = "select * from customer where idcurrency = '" + idcurrency + "'";
}
else if (customer == "")
{
Response.Write("<script>alert('No Id Inputted, Data Not Found.')</script>");
}
else
{
Response.Write("<script>alert('Invalid input.')</script>");
}
//DataSet and DataTable (get the data and display it into asp:repeater
selectedData = connector.ExecuteQuery(query);
dt = selectedData.Tables[0];
//Set PageData Settings
PagedDataSource pagedData = new PagedDataSource();
pagedData.DataSource = dt.DefaultView;
pagedData.AllowPaging = true;
//Set to 2 pages to be viewed
pagedData.PageSize = 2;
pagedData.CurrentPageIndex = PageNumber;
//Count to 2 pages to appear when clicking next or previous
int vcnt = dt.DefaultView.Count / pagedData.PageSize;
if (PageNumber == 1)
{
linkPrevious.Visible = false;
}
else if (PageNumber < 1)
{
linkPrevious.Visible = false;
}
else if (PageNumber > 0)
{
linkPrevious.Visible = true;
}
if (PageNumber == vcnt)
{
linkNext.Visible = false;
}
//Hide previous and next if it is firstpage and lastpage
else if(PageNumber < vcnt)
{
linkNext.Visible = !pagedData.IsLastPage;
linkPrevious.Visible = !pagedData.IsFirstPage;
}
//Binding the repeater
if (dt.Rows.Count > 0)
{
repeater.Visible = true;
repeater.DataSource = pagedData;
repeater.DataBind();
}
else
{
Response.Write("<script>alert('No Data Found.')</script>");
}
}
protected void linkNext_Click(object sender, EventArgs e)
{
linkNext.Visible = true;
PageNumber += 1;
BindRepeater();
}
protected void linkPrevious_Click(object sender, EventArgs e)
{
linkPrevious.Visible = true;
PageNumber -= 1;
BindRepeater();
}
}
}
Hope this is a good reference among programmers. :)

Related

IHtmlHelper does not contain a definition for 'RenderAction' error

I'm migrating my ASP .NET MVC app from .NET Framework 4.8 to .NET 6 and have encountered problem that Html.RenderAction method from System.Web.Mvc.Html namespace no longer works and I'm getting an error in my code:
if (Model.IsCrawler)
{
Html.RenderAction("GetLanguageSelector", "languageSelectorAsync", new { brand = Model.Layout.BrandShortName, cultureInfo = Model.CurrentPage.CurrentLanguage });
}
This method is accessing LanguageSelectorAsyncController:
public class LanguageSelectorAsyncController : Microsoft.AspNetCore.Mvc.Controller
{
private readonly IContentLoader contentLoader;
private readonly IContentLanguageAccessor contentLanguageAccessor;
public LanguageSelectorAsyncController(
IContentLoader contentLoader, IContentLanguageAccessor contentLanguageAccessor)
{
this.contentLoader = contentLoader;
this.contentLanguageAccessor = contentLanguageAccessor;
}
public Microsoft.AspNetCore.Mvc.ActionResult GetLanguageSelector(string brand, CultureInfo cultureInfo)
{
contentLanguageAccessor.Language = cultureInfo;
HomePage homePage = ContentReference.StartPage.Get<HomePage>();
if (homePage?.SiteSettingsLink != null)
{
SiteSettings settingsPage = contentLoader.Get<SiteSettings>(homePage.SiteSettingsLink, cultureInfo) ?? contentLoader.Get<SiteSettings>(homePage.SiteSettingsLink);
if (settingsPage != null)
{
if (brand == "rockstar")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.RockstarLanguageSelector);
}
else if (brand == "green")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.GreenLanguageSelector);
}
else if (brand == "rockfon")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.RockfonLanguageSelector);
}
else if (brand == "rockpanel")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.RockpanelLanguageSelector);
}
else if (brand == "lapinus")
{
return PartialView("Content/BrandSelectorBlock", settingsPage.LapinusLanguageSelector);
}
else if (brand == "language")
{
return PartialView("Content/LanguageSelectorBlock", settingsPage.LanguageSelector);
}
}
}
return null;
}
}
...which in turn uses views BrandSelectorBlock:
#model BrandSelectorBlock
#{
var list = Model.Continents;
var tabs = list.Item1;
var tabCount = "has-" + tabs.Count() + "-tabs";
var NoEurope = string.IsNullOrWhiteSpace(tabs.Where(x => x.Equals(Continents.Europe)).FirstOrDefault());
TempData.AddStyles(OrganismStyle.O23Tabs);
TempData.AddOrganismScripts(ViewScript.O23TabsView);
}
<header class="modal-multi-selector__header">
<div class="container">
<button type="button" class="modal-multi-selector__close js-lang__close"></button>
#if (!string.IsNullOrWhiteSpace(Model.BrandLogo))
{
<figure class="modal-multi-selector__logo">
#SvgHelper.GetSVG(Model.BrandLogo)
</figure>
}
<div class="modal-multi-selector__description">
<p class="body-text-2">#Html.ExtendedPropertyFor(x => x.BodyText)</p>
<p class="body-text-2 is-hidden">#Html.ExtendedPropertyFor(x => x.VisitorMessage)</p>
</div>
<h3 class="modal-multi-selector__title">#Html.ExtendedPropertyFor(x => x.Heading)</h3>
</div>
<div class="O23-tabs #tabCount is-filter">
<nav class="O23-tabs__nav">
<div class="container">
<ul class="O23-tabs__list is-hidden-sm">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var isActive = "";
if (tab.ToLower().Equals(Continents.Europe.ToLower()) || (NoEurope && i == 0))
{
isActive = "is-active";
}
<li class="O23-tabs__item #isActive">
<span>#tab</span>
</li>
}
<li class="O23-tabs__list__indicator"></li>
</ul>
<div class="O23-tabs__select is-hidden-md">
<div class="select">
<div class="select__wrap">
<div class="select__wrap__elem">
<select class="select__elem js-select" name="countries">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var selected = "";
if (tab.Equals(Continents.Europe) || (NoEurope && i == 0))
{
selected = "selected";
}
<option #selected value="#tab.ToLower()">#tab</option>
}
</select>
</div>
#SvgHelper.GetSVG("small-arrow-down")
</div>
</div>
</div>
</div>
</nav>
</div>
</header>
<div class="modal-multi-selector__content">
<div class="modal-multi-selector__content__inner">
<div class="container">
<ul class="modal-multi-selector__list">
#foreach (var langItem in list.Item2)
{
<li class="modal-multi-selector__item" data-country-code="#langItem.CountryCode.ToLower()" data-filter="#langItem.Continent.ToLower()">#langItem.DisplayString</li>
}
</ul>
</div>
</div>
</div>
And LanguageSelectorBlock:
#model LanguageSelectorBlock
#{
var list = Model.Continents;
var tabs = list.Item1;
var tabCount = "has-" + tabs.Count() + "-tabs";
TempData.AddOrganismScripts(ViewScript.O23TabsView);
}
<header class="modal-multi-selector__header">
<div class="container">
<button type="button" class="modal-multi-selector__close js-lang__close"></button>
#if (!string.IsNullOrWhiteSpace(Model.BrandLogo))
{
<figure class="modal-multi-selector__logo">
#SvgHelper.GetSVG(Model.BrandLogo)
</figure>
}
<h3 class="modal-multi-selector__title">#Model.Heading</h3>
</div>
<div class="O23-tabs #tabCount is-filter">
<nav class="O23-tabs__nav">
<div class="container">
<ul class="O23-tabs__list is-hidden-sm">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var isActive = "";
if (i == 0)
{
isActive = "is-active";
}
<li class="O23-tabs__item #isActive">
<span>#tab</span>
</li>
}
<li class="O23-tabs__list__indicator"></li>
</ul>
<div class="O23-tabs__select is-hidden-md">
<div class="select">
<div class="select__wrap">
<div class="select__wrap__elem">
<select class="select__elem js-select" name="countries">
#for (var i = 0; i < tabs.Count(); i++)
{
var tab = tabs.ElementAt(i);
var selected = "";
if (i == 0)
{
selected = "selected";
}
<option #selected value="#tab.ToLower()">#tab</option>
}
</select>
</div>
#SvgHelper.GetSVG("small-arrow-down")
</div>
</div>
</div>
</div>
</nav>
</div>
</header>
<div class="modal-multi-selector__content">
<div class="modal-multi-selector__content__inner">
<div class="container">
<ul class="modal-multi-selector__list">
#foreach (var langItem in list.Item2)
{
var active = langItem.CountryCode.Equals(ContentLanguage.PreferredCulture.Name, StringComparison.OrdinalIgnoreCase)
? "is-active" : "";
<li class="modal-multi-selector__item #active" data-filter="#langItem.Continent.ToLower()">#langItem.DisplayString</li>
}
</ul>
<div class="modal-multi-selector__more">
#Html.ExtendedPropertyFor(x => x.MoreInfoButton)
</div>
</div>
</div>
</div>
I have tried using Html.PartialAsync and Html.RenderPartialAsync methods, but they aren't quite like for like replacement for Html.RenderAction and so did not work. I have also read about ViewComponents, but I don't know how to implement them in my code.

After filtering/sorting how to make the pagination not reset to page 1 but stay at current page?

I'm using PagedList library for pagination and also have ordering and filtering. The problem is that after submit of order/filter request the pagination resets to page 1 but I have to keep it at current page? How can this be achieved? I also don't know if this is the right behavior but I was told to it is.
This is my controller:
public class ProductSearchBlockController : BlockController<ProductSearchBlock>
{
private readonly IRepository<Products> _productsRepository;
public ProductSearchBlockController(IRepository<Products> productsRepository)
{
_productsRepository = productsRepository;
}
public override ActionResult Index(ProductSearchBlock currentBlock)
{
if (Session[SessionConstants.Products] == null)
{
Session[SessionConstants.Products] = _productsRepository.All();
}
var sessionProducts = Session[SessionConstants.Products] as IEnumerable<Products>;
var searchString = Request.QueryString.Get(RequestQueryConstants.SearchString);
var orderBy = Request.QueryString.Get(RequestQueryConstants.OrderBy);
var pageNumber = Request.QueryString.Get(RequestQueryConstants.PageNumber);
if (string.IsNullOrEmpty(orderBy))
{
orderBy = "default";
}
if (!string.IsNullOrEmpty(searchString))
{
var result = sessionProducts.Where(p => p.OrganizaitonId.Contains(searchString) ||
p.ProductName.Contains(searchString)).ToList();
Session[SessionConstants.ProductsResult] = result;
}
else
{
var result = sessionProducts.ToList();
Session[SessionConstants.ProductsResult] = result;
}
var productsResult = Session[SessionConstants.ProductsResult] as List<Products>;
productsResult = TableDisplayHelper.OrderedProducts(orderBy, productsResult);
var viewModel = new ProductSearchBlockViewModel();
viewModel.Products = productsResult.ToPagedList(int.Parse(pageNumber), 2);
viewModel.PageNumber = int.Parse(pageNumber);
viewModel.OrderBy = orderBy;
viewModel.FilterBy = searchString;
viewModel.Options = currentBlock.Options;
return PartialView(viewModel);
}
public ActionResult GetTableData(string searchString, string orderBy, int? page)
{
if (searchString == null && orderBy == null)
{
return Redirect(PageHelper.CurrentPageUrl());
}
if (searchString != null)
{
page = 1;
}
int pageNumber = page ?? 1;
var orderByQuery = UriUtil.AddQueryString(PageHelper.CurrentPageUrl(), RequestQueryConstants.OrderBy, orderBy.ToString());
var SearchStringQuery = UriUtil.AddQueryString(orderByQuery, RequestQueryConstants.SearchString, searchString);
var finalUrl = UriUtil.AddQueryString(SearchStringQuery, RequestQueryConstants.PageNumber, pageNumber.ToString());
return Redirect(finalUrl);
}
This is the view:
<div class="block esproductsearchblock col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
<div class="es-product-search-block es-product-search-block-index b-spacing-default fonts-regular template-base block-wrapper">
<div class="template-search-block wrapper-fullsize" data-is-pagination-enabled="True" style="opacity: 1; pointer-events: auto;">
<section class="product-search wrapper-940" style="opacity: 1; pointer-events: auto;">
#using (Html.BeginForm("GetTableData", "ProductSearchBlock", FormMethod.Get))
{
<span>Order By</span>
<select id="orderBySelect" name="orderBy" aria-hidden="true">
#if (Model.Options != null)
{
foreach (var item in Model.Options)
{
if (Model.OrderBy == item.Trim().ToLower())
{
<option value="#item" selected>#item</option>
}
else
{
<option value="#item">#item</option>
}
}
}
</select>
<div class="search-field bottom-aligned-m">
<input id="search-field-inputid" class="search-field-input" name="searchString" placeholder="Search" value="#Model.FilterBy">
<i class="fa fa-close"></i>
</div>
<button class="btn">Submit Search</button>
<a class="btn" href="/ProductSearchBlock/GetTableData">Clear Search</a>
<div id="distribution-status-filter" data-distribution-status-filter-id="251" data-distributon-status-options="Phased out,Mature,Active"></div>
}
</section>
<div class="search-results-table wrapper-940">
<section class="results">
<div class="products">
#foreach (var product in Model.Products)
{
<div class="product product-data">
<div class="title-container">
<p class="product-name">#product.ProductName</p>
</div>
<div class="group">
<p class="indication">#product.OrganizaitonId</p>
</div>
<div class="price">
<h6>Price per Unit</h6>
<p class="small-text bold">
#product.Price <span class="product-price__currency-marker">€</span>
</p>
</div>
#using (Html.BeginForm("AddToCart", "ProductSearchBlock", FormMethod.Get))
{
<div class="float-container">
<div class="float-child">
<h6>Quantity</h6>
<input min="1" style="width:50%" type="number" name="quantity" value="0">
<input hidden type="number" name="id" value="#product.Id">
</div>
<div class="float-child">
<button class="cart-btn primary-btn">Add</button>
</div>
</div>
}
</div>}
</div>
#Html.PagedListPager(Model.Products, page => Url.Action("GetTableData", "ProductSearchBlock",
new
{
page,
orderBy = Model.OrderBy,
searchString = Model.FilterBy
}),
new PagedListRenderOptions
{
ContainerDivClasses = new List<string> { "pagination" }, LiElementClasses = new List<string> { "paginationSpan" }
});
</section>
</div>
</div>
</div>
Found a solution maybe there is a better version but current one works.
Added parameter pageNumber to form and changed form to post:
#using (Html.BeginForm("GetTableData", "ProductSearchBlock", new { pageNumber=Model.PageNumber}, FormMethod.Post))
In controller get the current page number and check if exists set page to current page
public ActionResult GetTableData(string searchString, string orderBy, int? page)
{
var currentPage = Request.QueryString.Get(RequestQueryConstants.PageNumber);
if (searchString == null && orderBy == null)
{
return Redirect(PageHelper.CurrentPageUrl());
}
if(currentPage != null)
{
page = int.Parse(currentPage);
}
var orderByQuery = UriUtil.AddQueryString(PageHelper.CurrentPageUrl(), RequestQueryConstants.OrderBy, orderBy.ToString());
var SearchStringQuery = UriUtil.AddQueryString(orderByQuery, RequestQueryConstants.SearchString, searchString);
var finalUrl = UriUtil.AddQueryString(SearchStringQuery, RequestQueryConstants.PageNumber, page.ToString());
return Redirect(finalUrl);
}

using selenium chromedriver to upload file

I'm working with selenium chromedriver. So far I have been able to log on, check a check box, navigate to another web page. I've hit a brick wall though when I get to the upload file page.
The form has 4 or 5 buttons that will open up a dialog box to pick a file off of the local hard drive. There is no input to put in directly. I think that when you click one of the buttons it executes a javascript function that choose a file.
Please look at the source code of this page and see if you have any ideas how to accomplish this:
^^^`enter code here<head><link rel="shortcut icon" href="/favicon.ico"/><title>NYWB-ECF v10.5.2 NextGen Production Database</title>
<script type="text/javascript">document.cookie = "PRTYPE=aty; path=/;"</script> <script>var default_base_path = "/"; </script> <link rel="stylesheet" type="text/css" href="/css/default.css"><script type="text/javascript" src="/lib/core.js"></script><script type="text/javascript" src="/lib/autocomplete.js"></script><script type="text/javascript" src="/lib/DisableAJTALinks.js"></script><script type="text/javascript">if (top!=self) {top.location.replace(location.href);}</script><script>var default_base_path = "/"; </script></head><body BGCOLOR=ffffff TEXT=000000 onLoad='SetFocus()'>
<div class="noprint">
<div id="topmenu" class="yuimenubar"><div class="bd">
<img id="cmecfLogo" class="cmecfLogo" src="/graphics/logo-cmecf-sm.png" alt="CM/ECF" title="" />
<ul class="first-of-type">
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?BankruptcyEvents&id=492888'>Ban</u>kruptcy <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?AdversaryEvents&id=492888'>A</u>dversary <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/iquery.pl'>Q</u>uery</a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?Reports&id=492888'>R</u>eports <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?Utilities&id=492888'>U</u>tilities <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='javascript: CMECF.MainMenu.searchPrompt();'>Searc</u>h</a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" onClick="CMECF.MainMenu.showHelpPage(''); return false">Help</a></li>
<li class="yuimenubaritem"><a class="yuimenubaritemlabel" href='/cgi-bin/login.pl?logout'>Log Out</a></li><li class='yuimenubaritem' id='placeholderForAlertsIcon'></li>
</ul></div>
<hr class="hrmenuseparator"></div></div>
<script type="text/javascript">
callCreateMenu=function(){
var fn = "CMECF.MainMenu.renderSimpleMenu";
if(typeof CMECF.MainMenu.renderSimpleMenu == 'function') {
CMECF.MainMenu.renderSimpleMenu();
}
}
if (navigator.appVersion.indexOf("MSIE")==-1){window.setTimeout( function(){ callCreateMenu(); }, 1);}else{CMECF.util.Event.addListener(window, "load", callCreateMenu());}</script> <div id="cmecfMainContent"><input type="hidden" id="cmecfMainContentScroll" value="0"><SCRIPT LANGUAGE="JavaScript">
var IsForm = false;
var FirstField;
function SetFocus() {
if(IsForm) {
if(FirstField) {
var ind = FirstField.indexOf('document.',0);
if(ind == 0)
{
eval(FirstField);
}
else
{
var Code = "document.forms[0]."+FirstField+".focus();";
eval(Code);
}
} else {
var Cnt = 0;
while(document.forms[0].elements[Cnt] != null) {
try {
if(document.forms[0].elements[Cnt].type != "hidden" &&
!document.forms[0].elements[Cnt].disabled &&
!document.forms[0].elements[Cnt].readOnly) {
document.forms[0].elements[Cnt].focus();
break;
}
}
catch(e) {}
Cnt += 1;
}
}
}
return(true);
}
</SCRIPT>
<div id="main-page-title" style="margin-bottom: .5em">
<font face="arial,helvetica" color="0000cc" size="4"><b><span id="main-page-title-content">Open New Bankruptcy Case</span></b></font>
</div> <FORM ENCTYPE='multipart/form-data' method=POST action="/cgi-bin/Dispatch.pl?127734820136425">
<!-ShowPage(CaseUpLoad.htm)->
<!-- RPM Packages: ao-bkecf-web-* -->
<!-- RPM Permissions: 444 -->
<!-- RPM Owner: nobody -->
<!-- RPM Group: nobody -->
<!-- RPM Flags: configure -->
<script src="/lib/CommonLib.js" language="Javascript"></script>
<SCRIPT LANGUAGE="JavaScript">
function CheckCreditorMatrix(input,lower,upper,field) {
var strng = "" + input;
var len = strng.length;
if (len < lower || len > upper) {
var msg = "The List of Creditors is empty or does not exist";
alert(msg);
if (field) {
field.focus();
field.select();
}
return 0;
} else if (len == 0) { return 2; }
else return 1;
}
</script>
<table cellpadding="5"><tr>
<td><b>Case information</b><br/>
<input name="case_1" type="file" size="40" />
<font size = "-1">c:\Debtor.txt</font>
</td>
</tr><tr>
<td><b>Petition</b><br/>
<input name="file_1" type="file" size="40" />
<font size = "-1">c:\Petition.pdf</font>
</td>
</tr><tr>
<td><b>List of creditors</b><br/>
<input name = "creditorMatrixFilename" type="hidden" />
<input name="file_1_MTX" type="file" size="40" onChange="document.forms[0].creditorMatrixFilename.value = this.value"/>
<font size = "-1">c:\Creditor.txt</font>
</td>
<script>
var numEvents = 1;
// record the names so we know if the user tried to upload a file, even if it is invalid
function AssignHiddenValues() {
document.forms[0].creditorMatrixFilename.value = document.forms[0].file_1_MTX.value;
for (var i = 0; i <= numEvents; i++) {
if(document.forms[0]["configured_file_"+i])
document.forms[0]["configured_filename_"+i].value = document.forms[0]["configured_file_"+i].value;
}
return 1;
}
</script>
</tr><tr>
<td><b>Chapter 13 plan (<em>chapter 13 only</em>)</b><br/>
<input name = "configured_filename_0" type="hidden" />
<input name="configured_file_0" type="file" size="40"
onChange="document.forms[0].configured_filename_0.value = this.value" />
<font size = "-1">c:\Plan.pdf</font>
</td>
</tr><tr>
<td><b>Certificate of credit counseling </b><br/>
<input name = "configured_filename_1" type="hidden" />
<input name="configured_file_1" type="file" size="40"
onChange="document.forms[0].configured_filename_1.value = this.value" />
<font size = "-1">c:\CCC.pdf</font>
</td>
</tr></table>
<script>numEvents = 2</script>
<SCRIPT LANGUAGE="JavaScript">
document.cookie = "DPFFuncs='CaseUpLoadCollectCaseInfo-'; path=/; |";
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
var timerId;
var BeenHere = 0;
IsForm = true;
function empty(s) {
var whitespace = " \ \
\
";
if(s == null || s.length == 0) {
return(true);
}
// Is s only whitespace characters?
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (whitespace.indexOf(c) == -1) return false;
}
return(true);
}
function ClearTimer() {
BeenHere = 0;
clearTimeout(timerId);
return(true);
}
var FormId = 0;
function ProcessForm() {
if(BeenHere == 1) {
return(false);
}
if( ! AssignHiddenValues() ) {return false}
if( ! CheckString(document.forms[0].case_1.value, 1, 1000, document.forms[0].case_1) ) {return false}
if( ! CheckString(document.forms[0].file_1.value, 1, 1000, document.forms[0].file_1) ) {return false}
if( ! CheckCreditorMatrix(document.forms[0].file_1_MTX.value, 1, 1000, document.forms[0].file_1_MTX) ) {return false}
BeenHere = 1;timerId=setTimeout("ClearTimer()",5000);document.forms[FormId].submit();return true }
function RunAfterClear() {
}
</SCRIPT>
<TABLE><TR> <TD><INPUT NAME="button1" Value='Next' TYPE= "button" ONCLICK="ProcessForm()" > <TD> <TD> <INPUT NAME="reset" TYPE="RESET" VALUE="Clear" onClick="setTimeout('RunAfterClear()',100)"></TD> </TR></TABLE></FORM></div></body></html>
}
You can click the choose file button , and use sendkeys to give your location of the file.
WebElement upload = driver.findElement(By.linkText("Upload a Document:( .tex, .txt, .doc, .docx, .odt, .pdf, .rtf )"));
upload.sendKeys("C:\path\File.txt");
Checkout this code.

How to fix code have select all asp:CheckBoxList within current table only in .NET C# same as "JQuery - Select All CheckBoxes within..." question?

How to fix code have select all asp:CheckBoxList within current table only in .NET C# same as "JQuery - Select All CheckBoxes within current table only" question ?
Because I try coding with sample but can't select all asp:CheckBoxList within current table only.
Link to "JQuery - Select All CheckBoxes within current table only" question.
My snipplet to describe problem.
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript"
src="//code.jquery.com/jquery-1.6.4.js"></script>
<style>
form , p , td, th{
font-size: 24px;
}
input.largerCheckbox
{
width: 22px;
height: 22px;
}
</style>
</head>
<body>
<h1>Show checkboxes:</h1>
<p><label><input type="checkbox" class="largerCheckbox" id="checkAll"/> Check all</label></p>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"><br><br>
<table id="myTable">
<tr class="header">
<th>Checkbox</th>
<th>Number</th>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle1" value="1"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle2" value="11"></td>
<td>11</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle3" value="111"></td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle4" value="1111"></td>
<td>1111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle5" value="11111"></td>
<td>11111</td>
</tr>
</table>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
<script>
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
</script>
</body>
</html>
My full source code.
https://github.com/doanga2007/CheckLoopQR3
Sample code at the bottom.
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR3.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<style>
#myInput {
font-size: 16px;
padding: 6px 20px 6px 10px;
border: 1px solid #ddd;
margin-bottom: 3px;
}
</style>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("CheckBox1");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<label>Input Number to Search </label>
<input type="text" id="myInput" onkeyup="myFunction()"><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR3
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 6; i++)
{
num *= i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Text 1 -> ", "Selected Text 2 -> ", "Selected Text 3 -> ",
"Selected Text 4 -> ", "Selected Text 5 -> "};
string[] texture2 = { " is Checkbox 1.", " is Checkbox 2.", " is Checkbox 3.",
" is Checkbox 4.", " is Checkbox 5."};
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
int a = CheckBox1.Items.IndexOf(listItem);
a = a + 1;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a - 1] + listItem.Text + texture2[a - 1];
lblvalues.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}
Good news : I have answer to fix code have select all asp:CheckBoxList within current table only in .NET C# same as "JQuery - Select All CheckBoxes within current table only" question.
Key of answer to "jQuery :visible Selector".
jQuery :
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox:visible").prop('checked', $(this).prop("checked"));
});
});
My snipplet to another solve problem in HTML.
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript"
src="//code.jquery.com/jquery-1.6.4.js"></script>
<style>
form , p , td, th{
font-size: 24px;
}
input.largerCheckbox
{
width: 22px;
height: 22px;
}
</style>
</head>
<body>
<h1>Show checkboxes:</h1>
<p><label><input type="checkbox" class="largerCheckbox" id="checkAll"/> Check all</label></p>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"><br><br>
<table id="myTable">
<tr class="header">
<th>Checkbox</th>
<th>Number</th>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle1" value="1"></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle2" value="11"></td>
<td>11</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle3" value="111"></td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle4" value="1111"></td>
<td>1111</td>
</tr>
<tr>
<td><input type="checkbox" class="largerCheckbox" name="vehicle5" value="11111"></td>
<td>11111</td>
</tr>
</table>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
<script>
$("#checkAll").change(function () {
$("input:checkbox:visible").prop('checked', $(this).prop("checked"));
});
</script>
</body>
</html>
My full source code.
https://github.com/doanga2007/CheckLoopQR3
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR3.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<style>
#myInput {
font-size: 16px;
padding: 6px 20px 6px 10px;
border: 1px solid #ddd;
margin-bottom: 3px;
}
</style>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox:visible").prop('checked', $(this).prop("checked"));
});
});
</script>
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("CheckBox1");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<label>Input Number to Search </label>
<input type="text" id="myInput" onkeyup="myFunction()"><br />
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR3
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 6; i++)
{
num *= i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Text 1 -> ", "Selected Text 2 -> ", "Selected Text 3 -> ",
"Selected Text 4 -> ", "Selected Text 5 -> "};
string[] texture2 = { " is Checkbox 1.", " is Checkbox 2.", " is Checkbox 3.",
" is Checkbox 4.", " is Checkbox 5."};
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
int a = CheckBox1.Items.IndexOf(listItem);
a = a + 1;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a - 1] + listItem.Text + texture2[a - 1];
lblvalues.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}

Sitecore Feed latest 2 items

I have a sitecore web part that I am trying to get to display the top 2 most current items by date. I am having trouble because I am only able to get the latest item to show.
For the ascx Code:
<asp:Repeater ID="newsContainer" runat="server">
<ItemTemplate>
<div class="newsItem">
<h2>News</h2>
<a href="<%# SitecoreUtility.NavigateUrl((Item)Container.DataItem)%>" class="newsHeadline">
<span> <sc:Date ID="Date1" Item="<%# Container.DataItem %>" Field="Posted-Date" Format="MM.dd.yyyy" runat="server" />
<sc:Text ID="Text1" Item="<%# Container.DataItem %>" Field="Title" runat="server" />
</span>
</a>
<!-- <p class="newsSummary">
<asp:Literal ID="litBody" runat="server" Text="<%# SitecoreUtility.TruncateByWords(((Item)Container.DataItem).Fields[Constants.Fields.BODY].Value, 20) %>"></asp:Literal>
...
+ More</p> -->
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Panel ID="pnlPagination" runat="server"></asp:Panel>
<asp:Panel ID="pnlArchive" runat="server">
<!-- <div class="newsArchiveLink">
View Archived News
</div> -->
</asp:Panel>
<asp:Panel ID="pnlCurrent" runat="server">
<div class="newsArchiveLink">
View Current News
</div>
</asp:Panel>
For the ASCX.CS File:
public partial class Homepage_NewsListing : BaseSublayout
{
int CurrentPage = 1;
int PageSize = Constants.Values.SEARCH_SMALL_LIST;
protected void Page_Load(object sender, EventArgs e)
{
CurrentPage = int.Parse(WebUtil.GetQueryString("page", "1"));
List<Item> newsListings = new List<Item>();
Item newsItems = SitecoreUtility.Db.GetItem(Constants.Items.NEWS);
if (WebUtil.GetQueryString("type", "") == "archive")
{
newsListings = newsItems.Children.Where(item =>
(SitecoreUtility.FormatDateAtMidnight(item, Constants.Fields.ARCHIVEDATE) <= DateTime.Now)
&&
(!string.IsNullOrEmpty(item.Fields[Constants.Fields.ARCHIVEDATE].Value))
).OrderBy(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList();
pnlArchive.Visible = false;
//pnlCurrent.Visible = true;
pnlCurrent.Visible = false;
}
else
{
newsListings = newsItems.Children.Where(item =>
(SitecoreUtility.FormatDateAtMidnight(item, Constants.Fields.ARCHIVEDATE) > DateTime.Now)
||
(string.IsNullOrEmpty(item.Fields[Constants.Fields.ARCHIVEDATE].Value))
).OrderBy(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList();
//pnlArchive.Visible = true;
pnlArchive.Visible = false;
pnlCurrent.Visible = false;
}
newsContainer.DataSource = DisplayResults(newsListings.OrderByDescending(item => item.Fields[Constants.Fields.POSTED_DATE].Value).ToList());
newsContainer.DataBind();
}
protected List<Item> DisplayResults(List<Item> results)
{
pnlPagination.Controls.Add(new Pager(results.Count, PageSize, CurrentPage).BuildPaging());
if (CurrentPage > 1)
return results.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();
return results.Take(PageSize).ToList();
}
}
I would first try to make your code a bit more simple (for debugging) and use a fast query to pull items within a date range.
var date = DateTime.Now.AddMonths(3);
var dateString = date.Year.ToString() + date.Month.ToString().PadLeft(2, '0') + date.Day.ToString().PadLeft(2, '0');
var newsList = Sitecore.Context.Database.SelectItems("fast:/sitecore/content/home/your-path-to-news/*[##templatename='Your template name' and #POSTED_DATE > '" + dateString + "']").ToList();
newsList = newsList.OrderByDescending(n => n.Fields["POSTED_DATE"].Value).Take(2).ToList();
newsContainer.DataSource = newsList;
newsContainer.DataBind();

Categories

Resources