How to bind data to grid column using array - c#

aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/HomeMaster.master" AutoEventWireup="true" CodeFile="V_MaterCode.aspx.cs" Inherits="V_MaterCode" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "V_MaterCode.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grd_mastercodes").append("<tr><td>" + data.d[i].Vendor + "</td><td>" + data.d[i].SearchTerm + "</td><td>" + data.d[i].Vendor_Name + "</td><td>" + data.d[i].Street + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td><td>" + data.d[i].PO_Box + "</td><td>" + data.d[i].Currency + "</td><td>" + data.d[i].Sales_Person + "</td><td>" + data.d[i].Telephone_Number + "</td><td>" + data.d[i].Ext_01 + "</td><td>" + data.d[i].Ext_02 + "</td><td>" + data.d[i].Minimum_Value + "</td><td>" + data.d[i].Post_Code + "</td><td>" + data.d[i].Group + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" LoadScriptsBeforeUI="false"
EnablePartialRendering="false">
</asp:ScriptManager>
<div class="contentarea">
<br />
<asp:Label ID="lblsub" Style="overflow-x: auto; margin-left: 20px;" runat="server" Text="Station master data entry" />
</div>
<div style="margin: 0 auto; overflow: auto; padding: 10px 20px;">
<asp:GridView ID="grd_mastercodes" runat="server" HeaderStyle-BackColor="#f79646" HeaderStyle-ForeColor="White"
HeaderStyle-Font-Bold="false" Font-Names="Calibri"
Font-Size="Medium" RowStyle-BackColor="White" HeaderStyle-BorderColor="Black"
AutoGenerateColumns="False" RowStyle-BorderColor="Black" OnRowCreated="grd_mastercodes_RowCreated">
</asp:GridView>
</div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using AjaxControlToolkit;
public partial class V_MaterCode : System.Web.UI.Page
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
bool rowset = false;
GridView dgv = new GridView();
// For First gridview
String[] gridColumnNames_mastercodes = { "Vendor Code", "Search Term", "Vendor Name", "Street", "City", "Country", "Post Box", "Currency", "Sales Person", "Telephone Number", "Ext_01", "Ext_02", "Minimum Value", "Post Code", "Group" };
String[] gridColumnwidth_mastercodes = { "50px", "200px", "200px", "150px", "100px", "100px", "100px", "100px", "150px", "150px", "150px", "150px", "100px", "100px", "100px" };
int[] gridColumnWidth_mastercodes = { 3, 15, 15, 13, 10, 10, 10, 10, 13, 13, 13, 13, 10, 10, 10 };
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
//For First gridview
DataTable dt = new DataTable();
for (int c = 0; c < gridColumnNames_mastercodes.Length; c++)
{
DataColumn dcol = new DataColumn(c.ToString(), typeof(System.Int32));
dcol.ColumnName = gridColumnNames_mastercodes[c];
dt.Columns.Add(dcol);
TemplateField tf = new TemplateField();
tf.HeaderStyle.Font.Bold = false;
tf.HeaderText = gridColumnNames_mastercodes[c];
tf.HeaderStyle.Width = new Unit(gridColumnwidth_mastercodes[c]);
grd_mastercodes.Columns.Add(tf);
}
for (int i = 0; i < 15; i++)
{
dt.Rows.Add(dt.NewRow());
}
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
BindColumnToGridview();
}
private void BindColumnToGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("Vendor");
dt.Columns.Add("Search Term");
dt.Columns.Add("Vendor Name");
dt.Columns.Add("Street");
dt.Columns.Add("City");
dt.Columns.Add("Country");
dt.Columns.Add("Post Box");
dt.Columns.Add("Currency");
dt.Columns.Add("Sales Person");
dt.Columns.Add("Telephone Number");
dt.Columns.Add("Ext_01");
dt.Columns.Add("Ext_02");
dt.Columns.Add("Minimum Value");
dt.Columns.Add("Post Code");
dt.Columns.Add("Group");
dt.Rows.Add();
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
//grd_mastercodes.Rows[0].Visible = false;
}
[WebMethod]
public static UserDetails[] BindDatatable()
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
DataTable dt = new DataTable();
List<UserDetails> details = new List<UserDetails>();
using (SqlConnection con = new SqlConnection(connectionstring))
{
using (SqlCommand cmd = new SqlCommand("Select * From ArR_VendorMaster", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.Vendor = dtrow["Vendor"].ToString();
user.SearchTerm = dtrow["SearchTerm"].ToString();
user.Vendor_Name = dtrow["Vendor_Name"].ToString();
user.Street = dtrow["Street"].ToString();
user.City = dtrow["City"].ToString();
user.Country = dtrow["Country"].ToString();
user.PO_Box = dtrow["PO_Box"].ToString();
user.Currency = dtrow["Currency"].ToString();
user.Sales_Person = dtrow["Sales_Person"].ToString();
user.Telephone_Number = dtrow["Telephone_Number"].ToString();
user.Ext_01 = dtrow["Ext_01"].ToString();
user.Ext_02 = dtrow["Ext_02"].ToString();
user.Minimum_Value = dtrow["Minimum_Value"].ToString();
user.Post_Code = dtrow["Post_Code"].ToString();
user.Group = dtrow["Group"].ToString();
details.Add(user);
}
}
}
return details.ToArray();
}
public class UserDetails
{
public string Vendor { get; set; }
public string SearchTerm { get; set; }
public string Vendor_Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PO_Box { get; set; }
public string Currency { get; set; }
public string Sales_Person { get; set; }
public string Telephone_Number { get; set; }
public string Ext_01 { get; set; }
public string Ext_02 { get; set; }
public string Minimum_Value { get; set; }
public string Post_Code { get; set; }
public string Group { get; set; }
}
//For First Gridview
protected void grd_mastercodes_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int rc = 0; rc < grd_mastercodes.Columns.Count; rc++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "Excel_mastercodes" + e.Row.RowIndex + "_" + rc;
txtBox.MaxLength = gridColumnWidth_mastercodes[rc];
txtBox.Width = new Unit(gridColumnwidth_mastercodes[rc]);
txtBox.BorderStyle = BorderStyle.None;
e.Row.Cells[rc].Controls.Add(txtBox);
e.Row.Cells[rc].Attributes.Add("onKeyDown", "enter(this);");
if (rc == 3)
txtBox.Style["text-align"] = "left";
else
txtBox.Style["text-align"] = "center";
}
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
}
}
I need to bind data but it displaying column name only . It's not binding any data . weather i am doing in a correct . If any body knows how to get data please suggest me. I am using array and i am not sure how to bind data in array . I need your help

Related

How do you move data from one cell in one row of a web grid to another cell in another row that is empty using jQuery?

I am kind of lost when it comes to jQuery sometimes, though I know there is a way! How do you update or move three cells data to another row based on the rows id to where the row is green (empty cells)? The row column ID name is "LocationID". MVC application using a web grid. What I am trying to do is when I check the row, use the drop-down that has the id, send the data to that row where the id exists populating the three empty cells in green with the current columnar data row that is checked. Any help would be greatly appreciated!
WebGrid below:
enter
<div id="content">
#webGrid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
//alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
htmlAttributes: new { #id = "webGrid" },
columns: webGrid.Columns(
webGrid.Column(header: "Actions", format:#<span class="link">
<!--Add Checkbox here-->
<!-- Note: We can add clickable rows as an option for user using a checkbox, one
selects the data move and the other move to selection. -->
#Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new { #Class =
"SelectedMoveIsChecked", #id = "SelectedMoveIsChecked", #checked = false })
#Html.CheckBoxFor(model => model.SelectedMoveToChecked, new { #Class =
"SelectedMoveToChecked", #id = "SelectedMoveToChecked", #checked = false })
<!-- Html.CheckBox("isActive", false, item.isSelectdRow, true, new { id =
"CheckBoxSelectedBeginMove", Class = "CheckBoxIsSelected" })
Html.CheckBoxFor(Model.Input_Location, item.isSelectdRow, new { = "'SelectedRows'",
data_val = item.Location })
-->
<a class="Edit" href="javascript:;">Edit</a>
<a class="Clear" href="javascript:;">Clear</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</span>),
webGrid.Column(header: "Location", format: #<div>
<label id="LocationLbl" class="label">#item.Location</label>
<input id="Location" class="text" type="text" value="#item.Location" style="display:none"
/><br />
#Html.DropDownListFor(model => model.LocationAppended, Model.LocationAppended,
"Section/Location", new { IReadOnlyDictionary = "document.forms[0].submit();", #id =
"RowLocationDropDownList", #class = "RowLocationDropDownList", #visibility = "hidden",
#placeholder = "Location" })
</div>, style: "Location"),
webGrid.Column(header: "Section", format: #<div>
<label id="SectionLbl" class="label">#item.Section</label>
<input id="Section" class="text" type="text" value="#item.Section" style="display:none" />
</div>, style: "Section"),
webGrid.Column(header: "TrailerNumber", format: #<div>
<label id="TrailerNumberLbl" class="label">#item.TrailerNumber</label>
<input id="TrailerNumber" class="text" type="text" value="#item.TrailerNumber"
style="display:none" />
</div>, style: "TrailerNumber"),
webGrid.Column(header: "CarrierName", format: #<div>
<label id="CarrierNameLbl" class="label">#item.CarrierName</label>
<input id="CarrierName" class="text" type="text" value="#item.CarrierName"
style="display:none" />
</div>, style: "CarrierName"),
webGrid.Column(header: "LoadCommodityStatus", format: #<div>
<label id="LoadCommodityStatusLbl" class="label">#item.LoadCommodityStatus</label>
<input id="LoadCommodityStatus" class="text" type="text" value="#item.LoadCommodityStatus"
style="display:none" />
</div>, style: "LoadCommodityStatus"),
webGrid.Column(header: "DateLoaded", format: #<div>
<label id="DateLoadedLbl" class="label">#item.DateLoaded</label>
<input id="DateLoaded" class="text" type="text" value="#item.DateLoaded" style="display:none"
/>
</div>, style: "DateLoaded"),
webGrid.Column(header: "UserName", format: #<div>
<label id="UserNameLbl" class="label">#item.UserName</label>
<input id="UserName" class="text" type="text" value="#item.UserName" style="display:none" />
</div>, style: "UserName"),
webGrid.Column(header: "PlantLocation", format: #<div>
<label id="PlantLocationLbl" class="label">#item.PlantLocation</label>
<input id="PlantLocation" class="text" type="text" value="#item.PlantLocation"
style="display:none" />
</div>, style: "PlantLocation"),
webGrid.Column(header: "RowPageID", format: #<div>
<label id="LocationIDLbl" class="label">#item.LocationID</label>
</div>, style: "LocationID"))),
<div id="RowCountBpttom"><b>Records: #firstRecord - #lastRecord of
#webGrid.TotalRowCount</b></div>
</div>
<br />
<div class="WebGridTable">
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">
</script>
<script src="~/Scripts/YardDogAdmin.js"></script>
</body>
jQuery Below:
code here
enter
$('select.RowLocationDropDownList').attr('disabled', true);
$(".SelectedMoveIsChecked").change(function (i, row) {
$actualRowColorRed = $(row);
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {
$("select.RowLocationDropDownList").change(function (i, row) {
$actualRowColorRed = $(row);
//Checks to see if the checkbox is checked, display the alert showing data and color the row red again.
/////// if ($('.SelectedMoveIsChecked').is(':checked') == true) {
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[0];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[1];
var RowLocation = ret[2];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
// var ConfirmStr = " <b>Are you sure, you want to move this row From: </b>" + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
// alert("Alert " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?"
// );
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
//Add new values to (TrailerNumber, CarrierName, LoadCommodityStatus, DateLoaded, UserName).
//Note: Get the UserName currently using the Yard Dog Application.
/// $('#webGrid').closest('tr').find('#TrailerNumber').val();
/// $("#webGrid tbody tr").each(function (i, row) {
// $('#webGrid tbody tr').find('#LocationID'.val(RowLocationIDNum); //= RowLocationIDNum).append('#TrailerNumber'.val(CurrentRowTrailerNumber));
$("body").on("change", "select.RowLocationDropDownList", function () {
// $("body").on("click", "#webGrid TBODY .Update", function () {
// $("#content").on("click", "#webGrid INPUT", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
}
});
//// $('#webGrid tbody tr').find('#LocationID').val(RowLocationIDNum) = customer;
var RowExchange = $(RowLocationID).closest("tr");
var ToRow = {};
ToRow.LocationID = row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
/*
ToRow.LocationID = RowExchange.find('#LocationID').append(RowLocationID) ;
ToRow.UserName = RowExchange.find('.UserName').append(row.find(".UserName").find(".label").html());
ToRow.Location = RowExchange.find('.Location').append(row.find(".Location").find(".label").html());
ToRow.Section = RowExchange.find('.Section').append(row.find(".Section").find(".label").html());
ToRow.TrailerNumber = RowExchange.find('.TrailerNumber').append(ToRow.TrailerNumber);
ToRow.CarrierName = RowExchange.find('.CarrierName').val().append(ToRow.CarrierName);
ToRow.LoadCommodityStatus = RowExchange.find('.LoadCommodityStatus').append(ToRow.LoadCommodityStatus);
ToRow.DateLoaded = RowExchange.find('.DateLoaded').append(row.find(".DateLoaded").find(".label").html());
ToRow.PlantLocation = RowExchange.find('.PlantLocation').append(row.find(".PlantLocation").find(".label").html());
*/
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) +'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 777);
});
}
else {
confirm_value.value = "Cancel";
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
code here
Controller:
enter [HttpPost]
public ActionResult UpdateRowExchange(LocationData ToRow)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == ToRow.LocationID
select c).FirstOrDefault();
//Check for Duplicates.
///FindDuplicates(customer);
//HighlightDuplicate(webGrid);
//x => customer.TrailerNumber == x.TrailerNumber && x.TrailerNumber == customer.TrailerNumber //errases all data except the first cell TrailerNumber.
if (ToRow.UserName != null) updatedCustomer.UserName = ToRow.UserName.ToUpper();
else updatedCustomer.UserName = ToRow.UserName = null;
/*
if (customer.Location != null) updatedCustomer.Location = customer.Location.ToUpper();
else updatedCustomer.Location = customer.Location = null;
if (customer.Section != null) updatedCustomer.Section = customer.Section.ToUpper();
else updatedCustomer.Section = customer.Section = null;
*/
if (ToRow.TrailerNumber != null) updatedCustomer.TrailerNumber = ToRow.TrailerNumber.ToUpper();
else updatedCustomer.TrailerNumber = ToRow.TrailerNumber = null;
if (ToRow.CarrierName != null) updatedCustomer.CarrierName = ToRow.CarrierName.ToUpper();
else updatedCustomer.CarrierName = ToRow.CarrierName = null;
if (ToRow.LoadCommodityStatus != null) updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus.ToUpper();
else updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus = null;
if (ToRow.DateLoaded != null) updatedCustomer.DateLoaded = ToRow.DateLoaded.ToUpper();
else updatedCustomer.DateLoaded = ToRow.DateLoaded = null;
/*
if (customer.PlantLocation != null) updatedCustomer.PlantLocation = customer.PlantLocation.ToUpper();
else updatedCustomer.PlantLocation = customer.PlantLocation = null;
*/
//Create today's Date for a timestamp of inputs.
DateTime now = DateTime.Today;
ToRow.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
updatedCustomer.DateLoaded = ToRow.DateLoaded;
entities.SaveChanges();
//Refresh(out, customer.ToString());
}
return new EmptyResult();
}
code here
Model below:
enter code here
namespace YardDog.Model
{
public class YardDogModel
{
ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
//Two Properties for DropDownList.
public List<LocationData> LocationDatas { get; set; }
//public List<LocationData> Location { get; set; }
public List<LocationData> TrailerNumber { get; set; }
public List<SelectListItem> PlantLocation { get; set; }
public List<SelectListItem> Location { get; set; }
public List<SelectListItem> LocationList { get; set; }
public List<SelectListItem> SectionList { get; set; }
public List<SelectListItem> LocationAppended { get; set; }
[Display(Name = "Name")]
public List<SelectListItem> Section { get; set; }
public List<SelectListItem> ListDuplicates { get; set; }
public List<SelectListItem> UserName { get; set; }
//Allow the data to be transfered (Backend into SQL Server).
[Required]
public string Input_Location { get; set; }
[Required]
public string Input_Section { get; set; }
public string Input_TrailerNumber { get; set; }
public string Input_CarrierName { get; set; }
public string Input_CommodityLoadStatus { get; set; }
[Required]
public string Input_PlantLocation { get; set; }
//YardDogModel YardDogDatas = new YardDogModel();
//string TrailerNumber = Input_TrailerNumber;
public bool SelectedMoveIsChecked { get; set; } = false;
public bool SelectedMoveToChecked { get; set; } = false;
public string LocationAppendedLbl { get; internal set; }
//public string LocationAppended { get; internal set; }
public string RowLocationDropDownList { get; set; }
public int RowLocationIDNum { get; set; }
}
}
JavaScript:
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[2];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[0];
var RowLocation = ret[1];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
$("body").on("change", "select.RowLocationDropDownList", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum).
var ToRow = {};
ToRow.LocationID = RowLocationIDNum; //row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
});
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 500);
});
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 500);
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
});
}
});

FullCalendar not updating Database using asp.net webforms mssql ajax jquery

I am trying to use a fullcalendar module to see various events. So far only events from the database get populated onto the fullcalendar but any edit or delete or add operation do not get reflected in the database
I have used masterpage and this page is the contentpage
so the master page has style sheets and javascript files such as
<title>ASP.NET FullCalendar</title>
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/jquery-ui.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.css" rel="stylesheet" />
..
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.js"></script>
<script src="scripts/calendarscript.js" type="text/javascript"></script>
my aspx file:EventManagement.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div id="calendar">
</div>
<div id="updatedialog" style="font: 70% 'Trebuchet MS', sans-serif; margin: 50px;display: none;"
title="Update or Delete Event">
<table class="style1">
<tr>
<td class="alignRight">
Name:</td>
<td class="alignLeft">
<input id="eventName" type="text" size="33" /><br /></td>
</tr>
<tr>
<td class="alignRight">
Description:</td>
<td class="alignLeft">
<textarea id="eventDesc" cols="30" rows="3" ></textarea></td>
</tr>
<tr>
<td class="alignRight">
Start:</td>
<td class="alignLeft">
<span id="eventStart"></span></td>
</tr>
<tr>
<td class="alignRight">
End: </td>
<td class="alignLeft">
<span id="eventEnd"></span><input type="hidden" id="eventId" /></td>
</tr>
<tr>
<td>
<div class="ui-dialog-buttonset">
<asp:Button ID="Button1" runat="server" Text="Update" ></asp:Button>
<asp:Button ID="Button2" runat="server" Text="delete" ></asp:Button>
</div>
</td>
</tr>
</table>
</div>
<div id="addDialog" style="font: 70% 'Trebuchet MS', sans-serif; margin: 50px;" title="Add Event">
<table class="style1">
<tr>
<td class="alignRight">
Name:</td>
<td class="alignLeft">
<input id="addEventName" type="text" size="33" /><br /></td>
</tr>
<tr>
<td class="alignRight">
Description:</td>
<td class="alignLeft">
<textarea id="addEventDesc" cols="30" rows="3" ></textarea></td>
</tr>
<tr>
<td class="alignRight">
Start:</td>
<td class="alignLeft">
<span id="addEventStartDate" ></span></td>
</tr>
<tr>
<td class="alignRight">
End:</td>
<td class="alignLeft">
<span id="addEventEndDate" ></span></td>
</tr>
</table>
</div>
<div runat="server" id="jsonDiv" />
<input type="hidden" id="hdClient" runat="server" />
my code behind file: EventManagement.aspx.cs
public partial class EventManagement : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//this method only updates the title and description
//this is called when an event is clicked on the calendar
[System.Web.Services.WebMethod(true)]
public static string UpdateEvent(CalendarEvent cevent)
{
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(cevent.id))
{
if (CheckAlphaNumeric(cevent.name) && CheckAlphaNumeric(cevent.description))
{
EventDAO.updateEvent(cevent.id, cevent.name, cevent.description);
return "updated event with id:" + cevent.id + " update title to: " + cevent.name +
" update description to: " + cevent.description;
}
}
return "unable to update event with id:" + cevent.id + " title : " + cevent.name +
" description : " + cevent.description;
}
//this method only updates start and end time
//this is called when a event is dragged or resized in the calendar
[System.Web.Services.WebMethod(true)]
public static string UpdateEventTime(ImproperCalendarEvent improperEvent)
{
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(improperEvent.id))
{
EventDAO.updateEventTime(improperEvent.id, improperEvent.title, improperEvent.description,
Convert.ToDateTime(improperEvent.start),
Convert.ToDateTime(improperEvent.end),
improperEvent.allDay); //allDay parameter added for FullCalendar 2.x
return "updated event with id:" + improperEvent.id + " update start to: " + improperEvent.start +
" update end to: " + improperEvent.end;
}
return "unable to update event with id: " + improperEvent.id;
}
//called when delete button is pressed
[System.Web.Services.WebMethod(true)]
public static String deleteEvent(int id)
{
//idList is stored in Session by JsonResponse.ashx for security reasons
//whenever any event is update or deleted, the event id is checked
//whether it is present in the idList, if it is not present in the idList
//then it may be a malicious user trying to delete someone elses events
//thus this checking prevents misuse
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null && idList.Contains(id))
{
EventDAO.deleteEvent(id);
return "deleted event with id:" + id;
}
return "unable to delete event with id: " + id;
}
//called when Add button is clicked
//this is called when a mouse is clicked on open space of any day or dragged
//over mutliple days
[System.Web.Services.WebMethod(true)]
public static int addEvent(ImproperCalendarEvent improperEvent)
{
CalendarEvent cevent = new CalendarEvent()
{
name = improperEvent.title,
description = improperEvent.description,
start = Convert.ToDateTime(improperEvent.start),
end = Convert.ToDateTime(improperEvent.end),
allDay = improperEvent.allDay
};
if (CheckAlphaNumeric(cevent.name) && CheckAlphaNumeric(cevent.description))
{
int key = EventDAO.addEvent(cevent);
List<int> idList = (List<int>)System.Web.HttpContext.Current.Session["idList"];
if (idList != null)
{
idList.Add(key);
}
return key; //return the primary key of the added cevent object
}
return -1; //return a negative number just to signify nothing has been added
}
private static bool CheckAlphaNumeric(string str)
{
return Regex.IsMatch(str, #"^[a-zA-Z0-9 ]*$");
}
}
my JsonResponse.ashx file
public class JsonResponse : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
DateTime start = Convert.ToDateTime(context.Request.QueryString["start"]);
DateTime end = Convert.ToDateTime(context.Request.QueryString["end"]);
List<int> idList = new List<int>();
List<ImproperCalendarEvent> tasksList = new List<ImproperCalendarEvent>();
//Generate JSON serializable events
foreach (CalendarEvent cevent in EventDAO.getEvents(start, end))
{
tasksList.Add(new ImproperCalendarEvent {
id = cevent.id,
title = cevent.name,
start = String.Format("{0:s}", cevent.start),
end = String.Format("{0:s}", cevent.end),
description = cevent.description,
allDay = cevent.allDay,
});
idList.Add(cevent.id);
}
context.Session["idList"] = idList;
//Serialize events to string
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(tasksList);
//Write JSON to response object
context.Response.Write(sJSON);
}
public bool IsReusable {
get { return false; }
}
}
the CalendarEvent.cs class which has all properties regarding events
public class CalendarEvent
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public DateTime start { get; set; }
public DateTime end { get; set; }
public bool allDay { get; set; }
}
my dataaccess class-EventDAO.cs that speaks to the database
public class EventDAO
{
//change the connection string as per your database connection.
//string connectionString = ConfigurationManager.AppSettings["DBConnString"];
private static string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
//this method retrieves all events within range start-end
public static List<CalendarEvent> getEvents(DateTime start, DateTime end)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT id,name, description, eventstart, eventend, isFullDay,IsHalfDay,IsQuatDay FROM Events where eventstart between #start AND #end or eventend between #start and #end", con);
cmd.Parameters.AddWithValue("#start", start);
cmd.Parameters.AddWithValue("#end", end);
//cmd.Parameters.Add("#start", SqlDbType.DateTime).Value = start;
//cmd.Parameters.Add("#end", SqlDbType.DateTime).Value = end;
using (con)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
events.Add(new CalendarEvent() {
id = Convert.ToInt32(reader["id"]),
name = Convert.ToString(reader["name"]),
description = Convert.ToString(reader["description"]),
start = Convert.ToDateTime(reader["eventstart"]),
end = Convert.ToDateTime(reader["eventend"]),
allDay = Convert.ToBoolean(reader["isFullDay"])
});
}
}
return events;
//side note: if you want to show events only related to particular users,
//if user id of that user is stored in session as Session["userid"]
//the event table also contains an extra field named 'user_id' to mark the event for that particular user
//then you can modify the SQL as:
//SELECT event_id, description, title, event_start, event_end FROM event where user_id=#user_id AND event_start>=#start AND event_end<=#end
//then add paramter as:cmd.Parameters.AddWithValue("#user_id", HttpContext.Current.Session["userid"]);
}
//this method updates the event title and description
public static void updateEvent(int id, String title, String description)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Events SET name=#title, description=#description WHERE id=#event_id", con);
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = title;
cmd.Parameters.Add("#description", SqlDbType.VarChar).Value= description;
cmd.Parameters.Add("#event_id", SqlDbType.Int).Value = id;
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
//this method updates the event start and end time ... allDay parameter added for FullCalendar 2.x
public static void updateEventTime(int id,string title,string description, DateTime start, DateTime end, bool allDay)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Events SET name=#title,description=#description,eventstart=#event_start, eventend=#event_end, isFullDay=#all_day WHERE id=#event_id", con);
cmd.Parameters.Add("#event_start", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("#event_end", SqlDbType.DateTime).Value = end;
cmd.Parameters.Add("#event_id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("#all_day", SqlDbType.Bit).Value = allDay;
cmd.Parameters.AddWithValue("#title", title);
cmd.Parameters.AddWithValue("#description", description);
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
//this method deletes event with the id passed in.
public static void deleteEvent(int id)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("DELETE FROM Events WHERE (id = #event_id)", con);
cmd.Parameters.Add("#event_id", SqlDbType.Int).Value = id;
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
//this method adds events to the database
public static int addEvent(CalendarEvent cevent)
{
//add event to the database and return the primary key of the added event row
//insert
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Events(name, description, eventstart, eventend, isFullDay) VALUES(#title, #description, #event_start, #event_end, #all_day)", con);
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = cevent.name;
cmd.Parameters.Add("#description", SqlDbType.VarChar).Value = cevent.description;
cmd.Parameters.Add("#event_start", SqlDbType.DateTime).Value = cevent.start;
cmd.Parameters.Add("#event_end", SqlDbType.DateTime).Value = cevent.end;
cmd.Parameters.Add("#all_day", SqlDbType.Bit).Value = cevent.allDay;
int key = 0;
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
//get primary key of inserted row
cmd = new SqlCommand("SELECT max(id) FROM Events where name=#title AND description=#description AND eventstart=#event_start AND eventend=#event_end AND isFullDay=#all_day", con);
cmd.Parameters.Add("#title", SqlDbType.VarChar).Value = cevent.name;
cmd.Parameters.Add("#description", SqlDbType.VarChar).Value = cevent.description;
cmd.Parameters.Add("#event_start", SqlDbType.DateTime).Value = cevent.start;
cmd.Parameters.Add("#event_end", SqlDbType.DateTime).Value = cevent.end;
cmd.Parameters.Add("#all_day", SqlDbType.Bit).Value = cevent.allDay;
key = (int)cmd.ExecuteScalar();
}
return key;
}
}
another class used in between javascript and asp.net
ImproperCalendarEvent.cs
public class ImproperCalendarEvent
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
public bool allDay { get; set; }
}
the javascript file code -calendarscript.js
var currentUpdateEvent;
var addStartDate;
var addEndDate;
var globalAllDay;
function updateEvent(event, element) {
alert(event.description);
if ($(this).data("qtip")) $(this).qtip("destroy");
currentUpdateEvent = event;
$('#updatedialog').dialog('open');
$("#eventName").val(event.title);
$("#eventDesc").val(event.description);
$("#eventId").val(event.id);
$("#eventStart").text("" + event.start.toLocaleString());
if (event.end === null) {
$("#eventEnd").text("");
}
else {
$("#eventEnd").text("" + event.end.toLocaleString());
}
return false;
}
function updateSuccess(updateResult) {
alert(updateResult);
}
function deleteSuccess(deleteResult) {
alert(deleteResult);
}
function addSuccess(addResult) {
// if addresult is -1, means event was not added
// alert("added key: " + addResult);
if (addResult != -1) {
$('#calendar').fullCalendar('renderEvent',
{
title: $("#addEventName").val(),
start: addStartDate,
end: addEndDate,
id: addResult,
description: $("#addEventDesc").val(),
allDay: globalAllDay
},
true // make the event "stick"
);
$('#calendar').fullCalendar('unselect');
}
}
function UpdateTimeSuccess(updateResult) {
alert(updateResult);
}
function selectDate(start, end, allDay) {
$('#addDialog').dialog('open');
$("#addEventStartDate").text("" + start.toLocaleString());
$("#addEventEndDate").text("" + end.toLocaleString());
addStartDate = start;
addEndDate = end;
globalAllDay = allDay;
//alert(allDay);
}
function updateEventOnDropResize(event, allDay) {
//alert("allday: " + allDay);
var eventToUpdate = {
id: event.id,
start: event.start
};
if (event.end === null) {
eventToUpdate.end = eventToUpdate.start;
}
else {
eventToUpdate.end = event.end;
}
var endDate;
if (!event.allDay) {
endDate = new Date(eventToUpdate.end + 60 * 60000);
endDate = endDate.toJSON();
}
else {
endDate = eventToUpdate.end.toJSON();
}
eventToUpdate.start = eventToUpdate.start.toJSON();
eventToUpdate.end = eventToUpdate.end.toJSON(); //endDate;
eventToUpdate.allDay = event.allDay;
PageMethods.UpdateEventTime(eventToUpdate, UpdateTimeSuccess);
}
function eventDropped(event, dayDelta, minuteDelta, allDay, revertFunc) {
if ($(this).data("qtip")) $(this).qtip("destroy");
updateEventOnDropResize(event);
}
function eventResized(event, dayDelta, minuteDelta, revertFunc) {
if ($(this).data("qtip")) $(this).qtip("destroy");
updateEventOnDropResize(event);
}
function checkForSpecialChars(stringToCheck) {
//var pattern = /[^A-Za-z0-9 ]/;
//return pattern.test(stringToCheck);
return true;
}
function isAllDay(startDate, endDate) {
var allDay;
if (startDate.format("HH:mm:ss") == "00:00:00" && endDate.format("HH:mm:ss") == "00:00:00") {
allDay = true;
globalAllDay = true;
}
else {
allDay = false;
globalAllDay = false;
}
return allDay;
}
function qTipText(start, end, description) {
var text;
if (end !== null)
text = "<strong>Start:</strong> " + start.format("MM/DD/YYYY hh:mm T") + "<br/><strong>End:</strong> " + end.format("MM/DD/YYYY hh:mm T") + "<br/><br/>" + description;
else
text = "<strong>Start:</strong> " + start.format("MM/DD/YYYY hh:mm T") + "<br/><strong>End:</strong><br/><br/>" + description;
return text;
}
$(document).ready(function () {
// update Dialog
$('#updatedialog').dialog({
autoOpen: false,
width: 470,
buttons: {
"update": function () {
alert(currentUpdateEvent.title);
var eventToUpdate = {
id: currentUpdateEvent.id,
name: $("#eventName").val(),
description: $("#eventDesc").val()
};
PageMethods.UpdateEvent(eventToUpdate, updateSuccess);
$(this).dialog("close");
currentUpdateEvent.title = $("#eventName").val();
currentUpdateEvent.description = $("#eventDesc").val();
$('#calendar').fullCalendar('updateEvent', currentUpdateEvent);
},
"delete": function () {
if (confirm("do you really want to delete this event?")) {
PageMethods.deleteEvent($("#eventId").val(), deleteSuccess);
$(this).dialog("close");
$('#calendar').fullCalendar('removeEvents', $("#eventId").val());
}
}
}
});
//add dialog
$('#addDialog').dialog({
autoOpen: false,
width: 470,
buttons: {
"Add": function () {
//alert("sent:" + addStartDate.format("dd-MM-yyyy hh:mm:ss tt") + "==" + addStartDate.toLocaleString());
var eventToAdd = {
title: $("#addEventName").val(),
description: $("#addEventDesc").val(),
start: addStartDate.toJSON(),
end: addEndDate.toJSON(),
allDay: isAllDay(addStartDate, addEndDate)
};
if (checkForSpecialChars(eventToAdd.title) || checkForSpecialChars(eventToAdd.description)) {
alert("please enter characters: A to Z, a to z, 0 to 9, spaces");
}
else {
//alert("sending " + eventToAdd.title);
PageMethods.addEvent(eventToAdd, addSuccess);
$(this).dialog("close");
}
}
}
});
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var options = {
weekday: "long", year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today customBtn',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
customButtons: {
customBtn: {
text: 'Custom Button',
click: function () {
alert('This custom button is hot! 🔥\nNow go have fun!');
}
}
},
defaultView: 'agendaWeek',
eventClick: updateEvent,
selectable: true,
selectHelper: true,
select: selectDate,
editable: true,
events: "JsonResponse.ashx",
eventDrop: eventDropped,
eventResize: eventResized,
eventRender: function (event, element) {
//alert(event.title);
element.qtip({
content: {
text: qTipText(event.start, event.end, event.description),
title: '<strong>' + event.title + '</strong>'
},
position: {
my: 'bottom left',
at: 'top right'
},
style: { classes: 'qtip-shadow qtip-rounded' }
});
}
});
});

how to display Highcharts from database in C# .Net

I have seen this http://codepedia.info/chartjs-asp-net-create-pie-chart-with-database-calling-jquery-ajax-c/ link and followed every steps but dint get the output(i have used "public class cityPopulation") in code behind instead of asmx page will it be the error
</head>
<body>
<script>
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "aspchartjsdemo.aspx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
</script>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlyear" runat="server" >
<asp:ListItem>2010</asp:ListItem>
<asp:ListItem>2011</asp:ListItem>
<asp:ListItem>2012</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnCreatePieChart" runat="server" Text="Button" />
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
</div>
</form>
</body>
</html>
here is my Code Behind..Im Unable to Fetch the data from database.
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
using (NpgsqlConnection con = new NpgsqlConnection("Server=Localhost;Port=5432;User Id=postgres;Password=postgres;Database=database4;"))
{
string myQuery = "SELECT id_, city_name, population FROM tb_city_population WHERE year_of = #year";
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.CommandText = myQuery;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#year", pData[0]);
cmd.Connection = con;
con.Open();
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
cityPopulation cpData = new cityPopulation();
cpData.city_name = dr["city_name"].ToString();
cpData.population = Convert.ToInt32(dr["population"].ToString());
p.Add(cpData);
}
}
}
return p;
}
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
Any Help Highly appreciated..
This is how I build the Pie:
<div id="pieChart"></div>
<script type="text/javascript" src="highcharts.js"></script>
<script>
var myPieData = [ ['AAA', 34.03], ['BBB', 27.01], ['CCC', 18.77], ['DDD', 11.01], ['EEE', 5.91], ['FFF', 3.27] ];
chart = new Highcharts.Chart({
chart: {
renderTo: 'pieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'My PieData'
},
tooltip: {
pointFormat: '<b>{point.percentage:.2f}%</b>',
percentageDecimals: 2
},
plotOptions: {
pie: {
allowPointSelect: false,
cursor: 'default',
dataLabels: {
enabled: false,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [{
type: 'pie',
name: '',
data: myPieData
}]
});
</script>
The part you have to replace with your own data is [ ['Label A', 34.03], ['Label B', 27.01], ['Label C', 18.77], ['Label D', 11.01], ['Label E', 5.91], ['Label F', 3.27] ]
Of course the total value of all the data should be 100.00%
You can do that with a Literal or a string that is filled with content from code behind: var myPieData = [ <%= pieData %> ] or get it from an external source.
Depending on your localization settings, a numeric value can contain a "," instead of a "." (23,59 or 23.59). If your localization uses a "," you will have to replace that with a dot.
UPDATE
As requested an example of how to get a correct string that you can use to build the pie. This should get you started... Just make sure that population is in percentages, not absolute numbers.
public string getCityPopulation(List<string> pData)
{
StringBuilder sb = new StringBuilder();
string myQuery = "SELECT city_name, population FROM tb_city_population WHERE (year_of = #year)";
using (SqlConnection connection = new SqlConnection(Common.connectionString))
using (SqlCommand command = new SqlCommand(myQuery, connection))
{
command.Parameters.AddWithValue("#year", pData[0]);
try
{
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
sb.Append("[");
sb.Append("'" + dr["city_name"].ToString() + "'");
sb.Append(", ");
sb.Append(dr["population"].ToString().Replace(",", "."));
sb.Append("],");
}
}
}
catch
{
//error connecting\reading the database
}
}
return "[ " + sb.ToString().TrimEnd(',') + " ]";
}

How to create pagination in asp.net mvc

I want to make pagination with 5 articles per page using asp.net MVC,
what code should I add?
Here my controller:
using CBA.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CBA.ViewModels;
using System.Data;
namespace CBA.Controllers
{
public class EventController : Controller
{
private ModelEntities db = new ModelEntities();
public ActionResult Index()
//public ActionResult Index(int page = 1, int pageSize 5)
{
EventDetailsViewModel eventDetail = new EventDetailsViewModel();
MasterEvents events = new MasterEvents();
eventDetail.Title = events.Title;
eventDetail.CreatedTime = events.CreatedTime;
eventDetail.Detail = events.DetailEvent;
eventDetail.CreatedBy = events.CreatedBy_Id;
eventDetail.Description = events.ShortDescription;
CBA.GetContent.GetContentSoapClient service = new CBA.GetContent.GetContentSoapClient();
string[] Content = service.GetContentText("Events", DateTime.Now.ToString("MM-dd-yyyy"), clsEncrypt.EncodeTo64(DateTime.Now.ToString("MM-dd-yyyy")));
if (Content[0] != null)
{
string id = Content[0];
string ContentText;
if (Content[1].Length == 0 && Content[2].Length == 0 && Content[3].Length == 0)
{
ContentText = "";
}
else
{
ContentText = "<div class=\"container\" #MARGIN-TOP# ><div class=\"row\"><div class=\"col-lg-10 col-lg-offset-1\">";
ContentText += "<div class=\"col-lg-12\" style=\"text-align:center;\"><h1>" + Content[1] + "</h1></div>";
ContentText += "<div class=\"col-lg-12\" style=\"text-align:center;\"><h2>" + Content[2] + "</h2></div>";
ContentText += "<div class=\"col-lg-12\"><div class=\"form-group\">" + HttpUtility.HtmlDecode(Content[3]).Replace("src=\"/", "src=\"" + System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"] + "/") + "</div>";
ContentText += "</div></div></div>";
}
DataTable dtSlider = service.GetContentImageSlider(int.Parse(id), DateTime.Now.ToString("MM-dd-yyyy"), clsEncrypt.EncodeTo64(DateTime.Now.ToString("MM-dd-yyyy")));
if (dtSlider.Rows.Count > 0)
{
string ContentSlider = "<div id=\"myCarousel\" class=\"carousel slide\"><ol class=\"carousel-indicators\">";
for (int i = 0; i < dtSlider.Rows.Count; i++)
{
if (i == 0)
{
ContentSlider += "<li data-target=\"#myCarousel\" data-slide-to=\"" + i.ToString() + "\" class=\"active\"></li>";
}
else
{
ContentSlider += "<li data-target=\"#myCarousel\" data-slide-to=\"" + i.ToString() + "\"></li>";
}
}
ContentSlider += "</ol><div class=\"carousel-inner\">";
for (int i = 0; i < dtSlider.Rows.Count; i++)
{
//dt.Columns.Add("ImageFile", typeof(string));
//dt.Columns.Add("HeaderText", typeof(string));
//dt.Columns.Add("ContentText", typeof(string));
string img = dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]);
if (i == 0)
{
ContentSlider +=
"<div class=\"item active\" style=\"background:url('" + dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]) + "') "
+ "no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; "
+ "-o-background-size: cover;background-size: cover;\">"
+ "<div class=\"container\">"
+ "<div class=\"carousel-caption\">"
+ "<div class=\"col-lg-6\" style='width:260px;'>"
+ "<h1>" + (string)dtSlider.Rows[i]["HeaderText"] + "</h1>"
+ "<p class=\"scroll_bni\" style='width: 260px;'>"
+ (string)dtSlider.Rows[i]["ContentText"]
+ "</p>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div>";
}
else
{
ContentSlider +=
"<div class=\"item\" style=\"background:url('" + dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]) + "') "
+ "no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; "
+ "-o-background-size: cover;background-size: cover;\">"
+ "<div class=\"container\">"
+ "<div class=\"carousel-caption\">"
+ "<div class=\"col-lg-6\" style='width:260px;'>"
+ "<h1>" + (string)dtSlider.Rows[i]["HeaderText"] + "</h1>"
+ "<p class=\"scroll_bni\" style='width: 260px;'>"
+ (string)dtSlider.Rows[i]["ContentText"]
+ "</p>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div>";
}
}
ContentSlider += "</div><a class=\"left carousel-control\" href=\"#myCarousel\" data-slide=\"prev\"><span class=\"glyphicon glyphicon-chevron-left\"></span></a><a class=\"right carousel-control\" href=\"#myCarousel\" data-slide=\"next\"><span class=\"glyphicon glyphicon-chevron-right\"></span></a></div>";
ViewBag.Carousel = ContentSlider;
}
else
{
ContentText = ContentText.Replace("#MARGIN-TOP#", "style=\"margin-top:60px;\"");
}
ContentText = ContentText.Replace("#MARGIN-TOP#", "");
ViewBag.Content = ContentText;
}
return View(db.MasterEvents.ToList());
}
public ActionResult ViewEvents(int id)
{
MasterEvents MasterEvents = db.MasterEvents.Find(id);
ViewBag.data = id;
return View();
}
}
}
Here my view:
#model IEnumerable<CBA.Models.MasterEvents>
#{
ViewBag.Title = "Recruitment - DDR Events";
ViewBag.lnkEvents = "active";
Layout = "~/Views/Shared/ContentFrontEnd.cshtml";
}
<!-- Carousel
================================================== -->
#Html.Raw(ViewBag.Carousel)
<!-- /.carousel -->
<!-- Content
================================================== -->
#Html.Raw(ViewBag.Content)
<!-- /.Content -->
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div class="container" style="background-color: white; border-radius: 0 0 15px 15px; margin-bottom: 40px;">
<div class="row" style="margin-top: 30px;">
<div class="col-lg-10 col-lg-offset-1">
#foreach (var item in Model)
{
<div class="blog-post">
<h2 class="blog-post-title">#Html.DisplayFor(modelItem => item.Title)</h2>
<p class="blog-post-meta">
Created Time #Html.DisplayFor(modelItem => item.CreatedTime)
<!--by #Html.DisplayFor(modelItem => item.CreatedBy_Id)</p>-->
<h2 class="blog-post-title">#Html.DisplayFor(modelItem => item.ShortDescription)</h2>
<div class="readmore">
<p>
#{
string parameterValue = "";
if (item.DetailEvent.ToString().Length < 100)
{
parameterValue = item.DetailEvent;
}
else
{
parameterValue = item.DetailEvent.ToString().Substring(0, 200);
}
}
#Html.Raw(parameterValue);
</p>
</div>
<br />
#Html.ActionLink("Read More..", "ViewEvents", "Event", new { id = 7 }, new { #class = "btn btn-primary btn-lg", style = "width:180px;" })
</p>
<p class="blog-post-meta">
Update Time #Html.DisplayFor(modelItem => item.UpdatedTime)
<p>
</div>
}
<nav>
<ul class="pager">
<li>Previous</li>
<li>Next</li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
Here my models:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace CBA.Models
{
public class MasterEvents
{
[Key]
[DisplayName("ID")]
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required(ErrorMessage = "Required Events Title")]
[DisplayName("Title")]
[StringLength(250)]
public string Title { get; set; }
[Required(ErrorMessage = "Required Short Description")]
[DisplayName("Short Description")]
[StringLength(250)]
public string ShortDescription { get; set; }
[Required(ErrorMessage = "Required Details")]
[DisplayName("Detail Events")]
[StringLength(20)]
public string DetailEvent { get; set; }
[DisplayName("Created Time")]
public System.DateTime? CreatedTime { get; set; }
[DisplayName("Updated Time")]
public System.DateTime? UpdatedTime { get; set; }
[DisplayName("Created By")]
public int? CreatedBy_Id { get; set; }
[DisplayName("Updated By")]
public int? UpdatedBy_Id { get; set; }
}
}
How to make pagination, I want to make pagination with 5 articles per page..
Pagination in any system generally involves taking a page number and a count per page in the controller method so that you can then pass these values to your search method in the business layer or data access layer to get only the content that you need.
So essentially:
Modify the Index controller method to something like this: Index(int page = 1, int countPerPage = 5)
This will allow you to pass the page number and count per page in the controller which you can then use to pass to the search method.
You will also need to create a UI which shows the page numbers. One way to calculate how many pages you will need to show is by returning the TOTAL number of items present in the search (from your search method) and then dividing this by the countPerPage value.
I hope this pushes you in the right direction.
Here are some resources for further reading:
How do I do pagination in ASP.NET MVC?
and
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
which should give you a better idea.

How to create multipe column on ajax auto complete?

I create a table for searching items on ajax auto complete, I want to design like that(Table-1):
There is my web service code:
[WebMethod]
public object[] GetResult(string prefixText, int count)
{
List<object> result;
result = new List<object>();
try
{
Some Database query...
while (rd.Read())
{
result.Add(new
{
ProductName = rd[0],
Pic= rd[1],
RecID = rd[2],
Properties= rd[3]
});
}
rd.Close();
con.Close();
}
catch (Exception ex)
{
}
return result.ToArray();
}
I add a List object for all data and its java script side:
<script type="text/javascript">
function onPopulated() {
var list = $find("ace").get_completionList();
var count = list.childNodes.length;
for (i = 0; i < count; i++) {
var item = list.childNodes[i]._value;
var name = item.ProductName ;
var kategory = item.Properties;
var RecID = item.RecID;
var Pic= item.Pic;
var url = "http://abc.com.tr/img/p_" + RecID + "_" + Pic+ "_01.jpg"
list.childNodes[i].innerHTML = '<span id="name"><table><tr style="width:260px;height:55px;" ><td><img width="50" height="50" style="position:relative;" src="' + url + '"/></td><td style="font-size:11px;font-weight:bold;min-height:20px;">'+ name + '</td></tr></table></span>';
//'<span id="name"><table style="width:260px;"><tr><td><img width="50" height="50" src="' + url + '"/></td><td><b style="font-size:12px;">' + name + '</b><br>' + kategory + '</td></tr></table></span>'
}
}
function onSelected() {
var i = $find("ace")._selectIndex;
var item = list.get_completionList().childNodes[i]._value;
$get("txtSearch").value = item.name;
}
</script>
i add a table it view like that(Table-2):
and finally its my ajax toolkit tag:
<asp:TextBox runat="server" ID="txtSearch" Width="261" />
<cc1:AutoCompleteExtender ID="txtSearch_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServicePath="WebService.asmx"
FirstRowSelected="true"
EnableCaching="false"
ServiceMethod="GetResult"
MinimumPrefixLength="1"
CompletionListCssClass="completionList"
CompletionListHighlightedItemCssClass="itemHighlighted"
CompletionListItemCssClass="listItem"
OnClientItemSelected="onSelected" OnClientPopulated="onPopulated"
BehaviorID="ace" TargetControlID="txtSearch">
</cc1:AutoCompleteExtender>
How to create table like table-1? Please help me Thanks for your answers
I think, the following link may help you : http://vincexu.blogspot.com/2009/01/custom-autocomplete-6-multicolumn.html
For the record pasting code from the above mentioned article.
ASPX
<head runat="server">
<title></title>
<link href="../Default.css" rel="stylesheet" type="text/css" />
<style>
.cloumnspan
{
width:35px;
padding:0px;
border-color:Black;
border-style:solid;
border-width:1px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1" />
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<ajaxToolkit:AutoCompleteExtender
runat="server" OnClientPopulated="dd" OnClientItemSelected="itemSelected"
BehaviorID="AutoCompleteEx"
ID="autoComplete1"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList5"
MinimumPrefixLength="2"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="8"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :">
</ajaxToolkit:AutoCompleteExtender>
</form>
<script type="text/javascript">
function itemSelected(ev)
{
var index=$find("AutoCompleteEx")._selectIndex;
var value=$find("AutoCompleteEx").get_completionList().childNodes[index]._value;
$find("AutoCompleteEx").get_element().value = value;
}
function dd()
{
var comletionList=$find("AutoCompleteEx").get_completionList();
for(i=0;i<comletionList.childNodes.length;i++) {
var itemobj=new Object();
var _data = comletionList.childNodes[i]._value;
itemobj.name= _data.substring(_data.lastIndexOf('|') + 1); // parse name as item value
comletionList.childNodes[i]._value = itemobj.name;
_data = _data.substring(0, _data.lastIndexOf('|'));
itemobj.age = _data.substring(_data.lastIndexOf('|') + 1);
_data = _data.substring(0, _data.lastIndexOf('|'));
itemobj.id = _data.substring(_data.lastIndexOf('|') + 1);
comletionList.childNodes[i].innerHTML = "<div class='cloumnspan' style='width:10%;float:left'>" + itemobj.id + "</div>"
+ "<div class='cloumnspan' style='width:70%;float:left'>" + itemobj.name + "</div>"
+ "<div class='cloumnspan' style='width:18%;'>" + itemobj.age + "</div>";
}
}
</script>
</body>
Web Method:
[WebMethod]
public string[] GetCompletionList5(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
if (prefixText.Equals("xyz"))
{
return new string[0];
}
Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char)random.Next(65, 90);
char c2 = (char)random.Next(97, 122);
char c3 = (char)random.Next(97, 122);
int id = i;
int age = random.Next(18, 70);
items.Add(id.ToString() + "|" + age.ToString() + "|" + prefixText + c1 + c2 + c3);
}
return items.ToArray();
}

Categories

Resources