I have one Update panel & in that update panel I have a session.
On Partial post back I have to change the value of session depending on the Dates.
But When I do the partial Postback session is not refreshed Or lost, Dont know .
On the button click I am changing the session values.
How can I achieve that
Here Is the HTML
<asp:UpdatePanel ID="UpdatePasanel1"
UpdateMode="Always"
ClientIDMode="AutoID"ChildrenAsTriggers="true" runat="server">
<ContentTemplate>
<div class="vendor_shift_top">
<div class="col-md-12">
<div class="cntrol_heading">
<div class="inner_cntrol_heading_right">
<div class="cls">
<div class="popup_inner">
Start Date:
</div>
<div class="popup_inner">
<asp:TextBox ID="txtStartDate" ReadOnly="false" AutoPostBack="false" CssClass="txt_80" runat="server"></asp:TextBox>
</div>
<div class="popup_inner">
End Date:
</div>
<div class="popup_inner">
<asp:TextBox ID="txtEndDate" ReadOnly="false" CssClass="txt_80" runat="server"></asp:TextBox>
</div>
<div class="popup_inner">
<asp:LinkButton ID="LinkButton1" ForeColor="White" OnClick="Button1_Click" runat="server"><img src="../images/search.png" /> Search</asp:LinkButton>
</div>
</div>
<script type="text/javascript">
//On Page Load
$(".cls1").click(function () {
$(".cls").toggle("blind", 100);
});
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
$(".cls1").click(function () {
$(".cls").toggle("blind", 100);
});
}
});
};
</script>
</div>
</div>
</div>
<div class="vendor_shift_top">
<div class="col-md-12 map_box">
<script type="text/javascript" class="s">
//On Page Load
$(function () {
var dataSource = [
<%=Session["TotalSalesPurchase"]%>
];
$("#chartContainer3").dxChart({
dataSource: dataSource,
commonSeriesSettings: {
argumentField: "year"
},
series: [
{ valueField: "Inward", name: "Purchase" },
{ valueField: "Outward", name: "Sales" },
],
argumentAxis: {
grid: {
visible: true
}
},
tooltip: {
enabled: true
},
legend: {
verticalAlignment: "bottom",
horizontalAlignment: "center"
},
commonPaneSettings: {
border: {
visible: true,
right: false
}
}
});
});
//On UpdatePanel Refresh
//var prm = Sys.WebForms.PageRequestManager.getInstance();
//if (prm != null) {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, e) {
//if (sender._postBackSettings.panelsToUpdate != null) {
var dataSource = [
<%=Session["TotalSalesPurchase22"]%>
];
$("#chartContainer3").dxChart({
dataSource: dataSource,
commonSeriesSettings: {
argumentField: "year"
},
series: [
{ valueField: "Inward", name: "Purchase" },
{ valueField: "Outward", name: "Sales" },
],
argumentAxis: {
grid: {
visible: true
}
},
tooltip: {
enabled: true
},
legend: {
verticalAlignment: "bottom",
horizontalAlignment: "center"
},
commonPaneSettings: {
border: {
visible: true,
right: false
}
}
});
//}
});
//};
</script>
<div id="chartContainer3"
class="overlap_cls" runat="server" style="width: 100%; height: 340px;"></div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="LinkButton1" EventName="Click" />
</Triggers>
< /asp:UpdatePanel>
C#
protected void Button1_Click(object sender, EventArgs e)
{
//Session.Remove("TotalSalesPurchase22");
cm.ds.Clear();
ArrayList arr = new ArrayList();
arr.Add("#StartDate|" + txtStartDate.Text + "");
arr.Add("#EndDate|" + txtEndDate.Text + "");
cm.sp_reader_execute("spSalesPurchase_LineChart_Order", arr);
string DisplayChartFormat = "";
while (cm.rs.Read())
{
string MonthYear = cm.rs["month"].ToString() + "-" + cm.rs["year"].ToString();
DisplayChartFormat += "{ year: '" + MonthYear + "', Inward: " + cm.rs["InWardQty"].ToString() + ", Outward: " + cm.rs["OutWardQty"].ToString() + " },";
}
string FinalDisplayFormat = DisplayChartFormat.Remove(DisplayChartFormat.Length - 1);
Session["TotalSalesPurchase22"] = FinalDisplayFormat;
ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", string.Format("alert('{0}');", Session["TotalSalesPurchase22"]), true);
}
Any Help will be appreciated
Thank You
Hardik Parmar.
use this code.
string FinalDisplayFormat = DisplayChartFormat.Remove(DisplayChartFormat.Length - 1);
Session["TotalSalesPurchase22"] = FinalDisplayFormat;
Response.Write(#"<script language='javascript'>alert('The following errors have occurred: \n" + Session["TotalSalesPurchase22"] + " .');</script>");
since your button is located inside the update panel, you should not use Async trigger for it. use a regular trigger and it will work fine:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="BT_Test" runat="server" Text="Button" OnClick="BT_Test_Click"></asp:Button>
<script>
alert(<%=Session["test"]%>);
</script>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="BT_Test"/>
</Triggers>
</asp:UpdatePanel>
c#:
protected void BT_Test_Click(object sender, EventArgs e)
{
Session["test"] = "2";
}
Related
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
}
}
}
}
}
I am still learning MVC. I am having problem with Partial View. I have a page with dropdown value. And whenever user choose the value, a partial page with datatable will appear.
Currently, i am thinking of using JQuery load function to load the page into the div tag. But the datatable is not showing. Is there something wrong with my code or is it any better way of doing this? Please help. Thank you.
My View:
#model MVCWeb.Models.DP_Table
#{
ViewBag.Title = "Data Patching";
}
<br />
<h2>#ViewBag.Title</h2>
<br />
<table class="table-striped table-responsive">
<tbody>
<tr>
<td width="40%">
<label class="control-label">Select Table</label>
</td>
<td width="10%">:</td>
<td width="*%">
#Html.DropDownListFor(Model => Model.DPTableID, new SelectList(Model.TableCollection,
"DPTableId", "TableName"), "Please Select", new { #id = "ddTableName", #class = "form-control" })
</td>
</tr>
<tr>
<td><br /></td>
</tr>
<tr>
<td>
<label class="control-label">Select Action</label>
</td>
<td>:</td>
<td>
#Html.DropDownList("Actions", #ViewBag.PatchingActions as List<SelectListItem>,
"Please Select", new { #id = "ddPatchingAction", #class = "form-control", #disabled = "disabled" })
</td>
</tr>
</tbody>
</table>
<br />
<div id="divPatching"></div>
#section scripts{
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
var ddTableValue, ddPatchingActionValue;
$('#ddTableName').change(function () {
ddTableValue = $('#ddTableName option:selected').val();
if (ddTableValue) {
$("#ddPatchingAction").prop("disabled", false);
} else {
$("#ddPatchingAction").prop("disabled", true);
}
});
$('#ddPatchingAction').change(function () {
ddPatchingActionValue = $('#ddPatchingAction option:selected').val();
if (ddPatchingActionValue) {
$("#divPatching").load('#Url.Action("GetPartialView", "DataPatching")');
}
});
</script>
}
My Controller:
public PartialViewResult GetPartialView()
{
return PartialView("~/Views/PatchingBatch/Index.cshtml");
}
My Partial View:
<a class="btn btn-success" style="margin-bottom:10px" onclick="AddUserForm('#Url.Action("AddUser", "Account")')"><i class="fa fa-plus"></i> Add New User</a>
<table id="batchTable" class="table-striped table-responsive">
<thead>
<tr>
<th>Username</th>
<th>Name</th>
<th>Email Address</th>
<th>Is Admin</th>
<th></th>
</tr>
</thead>
</table>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
#section scripts{
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
var popup, dataTable;
$(document).ready(function () {
dataTable = $("#batchTable").DataTable({
"ajax": {
"url": "/Account/GetDPUserList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Username", "name":"Username" },
{ "data": "Name", "name": "Name" },
{ "data": "Email", "name": "Email" },
{ "data": "IsAdmin", "name": "IsAdmin" },
{
"data": "DPUserID", "render": function (data) {
return "<a class='btn btn-primary btn-sm' onclick=EditUserForm('#Url.Action("UpdateUser", "Account")/" + data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left: 5px' onclick=Delete(" + data +")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
},
],
"processing": "true",
"serverSide": "true",
"order": [0, "asc"]
});
});
function AddUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Add User Account",
height: 250,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function EditUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Update User Account",
height: 410,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if (confirm("Are you sure you want to delete this data?")) {
$.ajax({
type: "POST",
url: '#Url.Action("DeleteUser", "Account")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
}
)
}
}
</script>
}
My Partial Controller:
public ActionResult Index()
{
return PartialView();
}
[HttpPost]
public ActionResult GetDPUserList()
{
//server side parameter
int start = Convert.ToInt32(Request["start"]);
int length = Convert.ToInt32(Request["length"]);
string searchValue = Request["search[value]"];
string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
string sortDirection = Request["order[0][dir]"];
List<DP_User> userList = new List<DP_User>();
using (DBModel db = new DBModel())
{
userList = db.DP_User.ToList<DP_User>();
userList = userList.ToList<DP_User>();
int totalrows = userList.Count();
//search
if (!string.IsNullOrEmpty(searchValue))
{
userList = userList.Where(x => (x.Username != null && x.Username.ToString().ToLower().Contains(searchValue)) ||
(x.Name != null && x.Name.ToString().ToLower().Contains(searchValue)) ||
(x.Email != null && x.Email.ToString().ToLower().Contains(searchValue))).ToList<DP_User>();
}
int totalrowsafterfilter = userList.Count();
//sorting
if (!string.IsNullOrEmpty(sortColumnName) && !string.IsNullOrEmpty(sortDirection))
{
userList = userList.OrderBy(sortColumnName + " " + sortDirection).ToList<DP_User>();
}
//paging
userList = userList.Skip(start).Take(length).ToList<DP_User>();
return Json(new { data = userList, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalrowsafterfilter },
JsonRequestBehavior.AllowGet);
}
}
1-Create One Partial View To Name Of Page
2-Create One Action
public ActionResult YourPage()
{
return PartialView("~/Views/Page.cshtml");
}
3-To Your View Create One div
<div id="MyDiv"></div>
4-Write This Code To script
$(document).ready(function () {
$.get("/Home/YourPage", function (data) {
$('#MyDiv').html(data);
});
});
If you are in ASP.NET core you can use this command
<partial name="_yourPartial" />
it will load the view for you from a method in the controller
if you are in an older version of ASP.NET you can use this older command
#Html.Partial("_yourPartial")
it works the same way, and avoid using jquery
you can also pass a model through it, using the command
#Html.Partial("_yourPartial", new { paramName = "foo" })
I have two dropdownlists namely ddlCountry and ddlState. I am using jquery clone() method to create dynamic dropdownlist controls of the ddlCountry and ddlState dropdownlists.
Here is my code:
<body>
<form id="form1" runat="server">
<asp:Panel ID="ddlPanel" runat="server">
<div>
<asp:Button ID="btnClone" Text="Clone" runat="server" />
</div>
<br />
<br />
<table>
<tr>
<td>Cateogry:
</td>
<td>
<div>
<asp:DropDownList ID="ddlCountryList" runat="server" class="ddlCountryClass"></asp:DropDownList>
</div>
</td>
<td>SubCategory:
</td>
<td>
<div>
<asp:DropDownList ID="ddlStateList" runat="server" class="ddlStateClass"></asp:DropDownList>
</div>
</td>
</tr>
<tr>
<td>
<div id="target">
</div>
</td>
<td>
<div id="target2">
</div>
</td>
</tr>
</table>
<asp:Button ID="btnGet" runat="server" Text="Get Values" OnClick="GetDropDownListValues" />
</asp:Panel>
</form>
<script type="text/javascript">
$(function () {
$("[id*=btnClone]").bind("click", function () {
var index = $("#target select").length + 1;
//Clone the DropDownList
var ddl = $("[id$=ddlCountryList]").clone(true);
//Set the ID and Name
ddl.attr("id", "ddlCountryList_" + index);
ddl.attr("name", "ddlCountryList_" + index);
ddl.append('<option selected="selected" value="0">Select Country</option>');
//[OPTIONAL] Copy the selected value
var selectedValue = $("[id$=ddlCountryList] option:selected").val();
ddl.find("option[value = '" + selectedValue + "']").attr("selected", "selected");
//Append to the DIV.
$("#target").append(ddl);
$("#target").append("<br /><br />");
return false;
});
});
$(function () {
$("[id*=btnClone]").bind("click", function () {
var index = $("#target2 select").length + 1;
var ddl = $("[id$=ddlStateList]").clone();
ddl.attr("id", "ddlStateList_" + index);
ddl.attr("name", "ddlStateList_" + index);
var selectedValue = $("[id$=ddlStateList] option:selected").val();
ddl.find("option[value = '" + selectedValue + "']").attr("selected", "selected");
$("#target2").append(ddl);
$("#target2").append("<br /><br />");
return false;
});
});
// Make Ajax call to fetch the state values.
$(function () {
$('#ddlStateList').attr('disabled', 'disabled');
$('#ddlStateList').attr('disabled', 'disabled');
$('#ddlStateList').append('<option selected="selected" value="0">Select State</option>');
$('#ddlCountryList').change(function () {
var $countryDropdown = $(this); // "this" is the event source
var country = $countryDropdown.val();
// Figure out the index of the country dropdown
var index = $countryDropdown.attr('id').split("_")[1] || "";
if (index) {
index = "_" + index;
}
var $stateDropdown = $("#ddlStateList" + index);
$stateDropdown.removeAttr("disabled");
$.ajax({
type: "POST",
url: "Default.aspx/BindStates",
data: "{'country':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$stateDropdown.html(options)
},
error: function (data) {
alert('Something Went Wrong')
}
});
});
});
</script>
I want to store the selected value of each in the country dropdownlists(not of ddlstate) such as ddlCountry,ddlcountry_1,ddlcountry_2 and so on....in an array.
How can i achieve it?
for(i=0; i < somecounter; i++){
string ddlCountry = "ddlcountry_" + i;
DropDownList ddl = (DropDownList)ddlPanel.FindControl(ddlCountry);
string value = ddl.SelectedValue.ToString();
}
you have to put some counter and every time you add new dropdownlist increase the counter by one. Then you have the number of the dynamically created dropdownlists
Editable Dropdownlist working fine in .aspx page referred from this link:
http://jqueryui.com/autocomplete/#combobox
But if i use same code in master page.. i am not getting the Output(Editable dropdownlist)..
what can i do?
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<style>
.custom-combobox
{
position: relative;
display: inline-block;
}
.custom-combobox-toggle
{
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input
{
margin: 0;
padding: 5px 10px;
}
</style>
<script>
(function($) {
$.widget("custom.combobox", {
_create: function() {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function(event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function() {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function() {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function() {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function(event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function() {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function() {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.autocomplete("instance").term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
$(function() {
$("#combobox").combobox();
$("#toggle").click(function() {
$("#combobox").toggle();
});
});
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<div class="ui-widget">
<%-- <select id="combobox" runat="server" >--%>
<asp:DropDownList ID="combobox" runat="server">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
<asp:ListItem Text="ABC" Value="1"></asp:ListItem>
<asp:ListItem Text="CBI" Value="2"></asp:ListItem>
<asp:ListItem Text="IBM" Value="3"></asp:ListItem>
</asp:DropDownList>
</div>
</div>
</asp:Content>
Anyone try this? Seems to do the job
http://xdsoft.net/jquery-plugins/editableselect/
I have a server control as below:
[DefaultProperty("ContentKey")]
[ToolboxData("<{0}:ContentRating runat=server></{0}:ContentRating>")]
public class ContentRating : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string ContentKey
{
get
{
String s = (String)ViewState["ContentKey"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["ContentKey"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
StringBuilder builder = new StringBuilder(#"<div id=""divContentRating"">
<div id=""divAskForRating"">
#Question
<br />
<a id=""likeIcon""><img src=""~/Content/Images/like.jpg""/></a>
<a id=""neutralIcon""><img src=""~/Content/Images/neutral.jpg""/></a>
<a id=""unlikeIcon""><img src=""~/Content/Images/unlike.jpg""/></a>
</div>
<div id=""divPositiveRating"">
<div>
<img src=""~/Content/Images/like.jpg""/> #PositiveAnswerMessage <br />
Güncelle
</div>
</div>
<div id=""divNegativeRating"">
<div>
<img src=""~/Content/Images/unlike.jpg""/> #NegativeAnswerMessage <br />
Güncelle
</div>
</div>
<div id=""divNeutralRating"">
<div>
<img src=""~/Content/Images/neutral.jpg""/> #NeutralAnswerMessage <br />
Güncelle
</div>
</div>
<input type=""hidden"" id=""HasRated"" value=""False"">
<input type=""hidden"" id=""Rate"" value=""Rate"">
<input type=""hidden"" id=""ContentKey"" value=""#ContentKey"">
<input type=""hidden"" id=""RatingId"" value=""RatingId"">
<script type=""text/javascript"">
$(document).ready(function () {
var protocol = location.protocol;
var host = window.location.host;
if ($(""#HasRated"").val() == """"True"")
{
var rate = $(""#Rate"").val();
if (rate == 1) {
setPositiveRatedView();
}
else if (rate == 0) {
setNeutralRatedView();
}
else if (rate == -1) {
setNegativeRatedView();
}
else {
setNotRatedView();
}
}
else {
setNotRatedView();
}
$(""#likeIcon"").click(function () {
alert(""like"");
setPositiveRatedView();
ratePage(1, """");
});
$(""#neutralIcon"").click(function () {
alert(""neutral"");
setNeutralRatedView();
ratePage(0, """");
});
$(""#unlikeIcon"").click(function () {
alert(""unlike"");
setNegativeRatedView();
//mkMPopClc('NegativeRatingReason', 200, 300, 0, 0);
});
$("".updateRate"").click(function () {
setNotRatedView();
});
// $('.clsStl').click(function () {
// ratePage(-1, """");
// $('.mkMPop').fadeOut();
// });
//
// $('#ShareComment').click(function () {
// ratePage(-1, $(""#Comment"").val());
// $('.mkMPop').fadeOut();
// });
function setNotRatedView() {
$(""#divNeutralRating"").fadeOut();
$(""#divPositiveRating"").fadeOut();
$(""#divAskForRating"").fadeIn();
$(""#divNegativeRating"").fadeOut();
}
function setPositiveRatedView()
{
$(""#divNegativeRating"").fadeOut();
$(""#divNeutralRating"").fadeOut();
$(""#divAskForRating"").fadeOut();
$(""#divPositiveRating"").fadeIn();
}
function setNegativeRatedView() {
$(""#divNeutralRating"").fadeOut();
$(""#divPositiveRating"").fadeOut();
$(""#divAskForRating"").fadeOut();
$(""#divNegativeRating"").fadeIn();
}
function setNeutralRatedView() {
$(""#divNegativeRating"").fadeOut();
$(""#divPositiveRating"").fadeOut();
$(""#divAskForRating"").fadeOut();
$(""#divNeutralRating"").fadeIn();
}
function ratePage(rating, comment)
{
//alert(rating + """" """" + comment);
var contentKey = $(""#ContentKey"").val();
var hasRated = $(""#HasRated"").val();
var ratingId = $(""#RatingId"").val();
$.getJSON(protocol + '//' + host + '/tr/Rating/RatePage?contentKey=' + contentKey + '&rating=' + rating + '&ratingUpdate=' + hasRated + '&ratingId=' + ratingId + '&comment=' + comment, function (data) {
$(""#HasRated"").val(data.HasRated);
$(""#Rate"").val(data.Rate);
$(""#ContentKey"").val(data.ContentKey);
$(""#RatingId"").val(data.RatingId);
$(""#Comment"").val(data.Comment);
});
}
});
</script>
</div>");
builder.Replace("#ContentKey", this.ContentKey);
output.Write(builder);
}
}
When I add my control to my web page, I see that control is rendering as I am expecting but the jquery scripts doesn't work. Is it wrong to keep scripting code in a server control? What can I do to solve this problem?
if ($(""#HasRated"").val() == """"True"")
I think you have too many quote characters there...