Call function on ButtonClick - javascript

I am trying to call function from .aspx to my JavaScript.
I try something like this
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Filter" Width="224px" OnClientClick="return BindToData();" />
And here is my JavaScript
<script type="text/javascript">
function GetSelectedReportName() {
return
document.getElementById('<%=ddlReportName.ClientID%>').options[document.getElementById('<%=ddlReportName.ClientID%>').selectedIndex].value;
}
function ShowReport() {
var reportName = GetSelectedReportName();
ASPxWebDocumentViewer1.OpenReport(reportName);
}
</script>
And here is my function which I need to call in ButtonClick
public void BindToData()
{
try
{
string connString = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
string strproc = "TestReport";
using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
sda.Fill(ds);
XtraReport report = new XtraReport
{
DataSource = ds,
DataMember = ds.Tables[0].TableName
};
string[] arrvalues = new string[ds.Tables[0].Rows.Count];
for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
{
//assign dataset values to array
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Creat"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Modif"].ToString();
}
ASPxWebDocumentViewer1.OpenReport(report);
ASPxWebDocumentViewer1.DataBind();
//gridview1.DataSource = ds;
//gridview1.DataBind();
}
}
catch (Exception)
{
throw;
}
}
I need to load filtered report in button click, since in JS I only load report, when I click in button I get only unfiltered data, when I debug application I see that I get filtered data, but problem can be only in JS. Any help will be appreciate
Here is reference page which I check:
Link 1
Link 2
Link 3

Related

alert message when i select wrong in drop down list

I have two drop down list one lets assume ddl1 and ddl2. Both dropdown list bind hard coded in aspx page i want if i select ddl2 value if i selected some value suppose its not related to ddl1 value then show me alert message Please help me
My codes
public void BindSub()
{
Cmd = new SqlCommand("SP_P_BindSub", Con.OpenConnection());
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlSBU.DataSource = dt;
ddlSBU.DataValueField = "ID";
ddlSBU.DataTextField = "SBU_Name";
ddlSBU.DataBind();
ddlSBU.Items.Insert(0, new ListItem("Select", "0"));
}
protected void ddlSBU_SelectedIndexChanged(object sender, EventArgs e)
{
Cmd = new SqlCommand("SP_P_BindDepartment", Con.OpenConnection());
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("#SBU_ID", ddlSBU.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlDepartment.DataSource = dt;
ddlDepartment.DataValueField = "ID";
ddlDepartment.DataTextField = "Department_Name";
ddlDepartment.DataBind();
ddlDepartment.Items.Insert(0, new ListItem("Select", "0"));
}
<script >
$(document).ready(function () {
$("#ddlemployeetype").change(function () {
value1 = document.getelementbytext("ddlemployeetype").value;
value2 = document.getelementbytext("ddlrole").value;
case "Employee":
document.getElementById("subcategory").options[0] = new Option("select", "");
document.getElementById("subcategory").options[1] = new Option("Cordinator", "Cordinator");
document.getElementById("subcategory").options[2] = new Option("Filecer", "Filecer");
break;
case "Contractor":
document.getElementById("subcategory").options[0] = new Option("select", "");
document.getElementById("subcategory").options[1] = new Option("Leader", "Leader");
document.getElementById("subcategory").options[2] = new Option("Member", "Member");
break;
break;
return true;
if (value1 != value2) {
alert("not related value");
}
});
});
</script>
my ddl1 values are Contractor and employee and ddl2 values are cordinator, leader, facilator, leader2, member.
Condition : facilator and cordinator belongs to employee if i selected somthing other then show me message its wrong selection
You can do this by using jQuery:
$(document).ready(function () {
$("#ddl1").change(function () {
value1 = document.getElementById("ddl1").value;
value2 = document.getElementById("ddl2").value;
// here write your business logic
if (value1 != value2) {
alert("not related value");
}
});
});

How to convert datatable to json string in c#

Its work perfect when data in the datatable is small i.e 10 columns and 300 rows. But when the amount of data in datatable is large it did not work.
Here is my code
[WebMethod]
public static string getData()
{
string _cs = "";
string _query = "";
OleDbConnection _conn = new OleDbConnection();
OleDbCommand _cmd = new OleDbCommand();
OleDbDataAdapter _da = new OleDbDataAdapter();
DataTable _dt = new DataTable();
try
{
_cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _path + ";Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";";
//_query = "SELECT * FROM [3123121288$A1:L290]"; work perfect
_query = "SELECT * FROM [3123121288$]"; //did not work
_conn.ConnectionString = _cs;
_cmd.Connection = _conn;
_cmd.CommandText = _query;
_da.SelectCommand = _cmd;
_da.Fill(_dt);
}
catch (Exception ex)
{ }
return JsonConvert.SerializeObject(_dt);
}

How populate database records into my table ajax

So i go this information and have a empty table name categorytable so i have to have records stored in categoryList for the below code to work. so what do i write in categoryList which is to fetch the record from my category manager and display the data from sql
</table>
<script>
$(document).ready(function () {
var categoryList = [];
var $courseTableElement = $('#categoryTable');
var $rowElement;
var $cellElement;
var index = 0;
for (index = 0; index < categoryList.length; index++) {
$rowElement = $('<tr></tr>');
$cellElement = $('<td></td>', { text: categoryList[index].CategoryName });
$rowElement.append($cellElement);
$cellElement = $('<td></td>', { text: categoryList[index].CategoryId });
$rowElement.append($cellElement);
$courseTableElement.append($rowElement);
}
});
</script>
public List<Category> getAllCategory(string inUserId)
{
DataSet ds = new DataSet();
List<Category> categoryList = new List<Category>();
string sqlText = "";
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn; //setup the
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
sqlText = "SELECT CategoryId,CategoryName,CreatedBy,CreatedAt,UpdatedBy,UpdatedAt " +
" FROM Category ";
cmd.CommandText = sqlText;
cmd.Parameters.Add("#inCurrentUserId", SqlDbType.VarChar, 200).Value = inUserId;
da.Fill(ds, "CategoryData");
cmd.CommandText = sqlText;
}//using SqlDataAdapter da
cn.Close();
}//using SQLCommand cmd
}//using SQLConnection cn
foreach (DataRow dr in ds.Tables["CategoryData"].Rows)
{
Category category = new Category();
category.CategoryId = Int32.Parse(dr["CategoryId"].ToString());
category.CategoryName = dr["CategoryName"].ToString();
category.CreatedBy = dr["CreatedBy"].ToString();
category.CreatedAt = DateTime.Parse(dr["CreatedAt"].ToString());
category.UpdatedBy = dr["UpdatedBy"].ToString();
category.UpdatedAt = DateTime.Parse(dr["UpdatedAt"].ToString());
categoryList.Add(category);
}
return categoryList;
}
You just need to make an ajax request to your server and grab that data. I'm making a couple of assumptions.
That getAllCategory is accessible to the frontend via webapi or something of the sort.
That getAllCategory will return proper json.
function getDataFromServer(url, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("get",url);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readystate === 4 && xmlhttp.status === 200){
//data was retrieved successfully.
callback(JSON.parse(xmlhttp.response));
}
}
xmlhttp.send();
}
$(document).ready(function () {
//the path to action must include the id in querystring
var url = 'path_to_action'
getDataFromServer(url, function(data){
var courseTableElement = $('#categoryTable');
for(var i = 0; i < data.length; i++){
var row = $('<tr></tr>');
var cell1 = $('<td></td>, { text: data[i].CategoryName } );
var cell2 = $('<td></td>, { text: data[i].CategoryId } );
row.append(cell1);
row.append(cell2);
courseTableElement.append(row);
}
}
});

How do I set my default checked checkbox on pageload for my latest date in checkboxlist instead of select all?

I have a checkboxlist in asp.net, populated by a stored procedure. While "Select All" option is done in aspx.
Currently im setting my "Select All" as default using javascript to do some enabling and disabling upon slect "Select All".
My problem now is that I do not want to set "Select All" as default but the latest date as default on page load? How can I do so when my dates are populated using stored procedure?
The below is how my checkboxlist lloks like with select all as default:
The below is what I want to achieve which is to get the latest date (2nd checkbox):
My codes for my checkboxlist:
<asp:CheckBoxList ID="Date_CBL" Class="checkboxlist" runat="server" AppendDataBoundItems="True" ViewStateMode="Enabled">
<asp:ListItem Text="Select All" Value="Select All"></asp:ListItem>
</asp:CheckBoxList>
My codes for javascript:
$(function () {
if ($("#hidden").val() == "") {
$("#Date_CBL :checkbox").removeAttr('disabled');
$("[id*=Date_CBL] input:checkbox").eq(1).prop("checked", true);
$("#hidden").val("set");
}
});
$(function () {
$("#Date_CBL :checkbox").change(function () {
var ischecked = $(this).is(":checked");
var val = $(this).val();
//alert(val);
if (val == "Select All") {
if (ischecked) {
$("#Date_CBL :checkbox").attr('disabled', 'disabled');
$(this).removeAttr('disabled');
$("#Date_CBL :checkbox").prop("checked", false);
$(this).prop("checked", true);
return;
} else {
$("#Date_CBL :checkbox").removeAttr('disabled');
return;
}
} else if (val != "Select All") {
if (ischecked) {
$("#Date_CBL :checkbox[value='Select All']").prop("checked", false);
}
}
});
});
My codes to populate my check box list:
using (SqlConnection conn = new SqlConnection(dbConn))
{
try //Call stored procedure
{
SqlCommand cmd = new SqlCommand(spddl, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
//Populate CheckBoxList list items from store procedure
if (!IsPostBack)
{
Date_CBL.DataSource = ds.Tables[0];
Date_CBL.DataTextField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataValueField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataBind();
Bindgridview()
}
conn.Close();
}
My codes in cs:
public void BindGridView()
{
DateTime choosenDate = DateTime.MinValue;
using (SqlConnection conn = new SqlConnection(dbConn))
{
using (SqlCommand cmd = new SqlCommand(spretrieve, conn))
{
//Bind selected CheckBoxList items into one string and pass into stored procedure as parameter
String selectedDATE = String.Empty;
if (Date_CBL.SelectedValue == "Select All")
{
selectedDATE = "DATA_DATE";
}
else
{
foreach (ListItem item in Date_CBL.Items)
{
if (item.Selected)
{
DateTime dtTemp = Convert.ToDateTime(item.Value);
selectedDATE += "'" + dtTemp.ToString("yyyy-MM-dd") + "',";
}
}
selectedDATE = selectedDATE.Substring(0, selectedDATE.Length - 1);
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#DATE", SqlDbType.VarChar).Value = selectedDATE;
string query = cmd.CommandText;
//Populate grid view
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Gridview1.DataSource = ds.Tables[0];
Gridview1.DataBind();
Thus how can I always set my latest date which will be the 2nd check box to be default upon page load?
Please advice thanks.
You might need to go learn about Page Event
What load first...
UPDATE CODE
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Variable
string dbConn = string.Empty;
string spddl = string.Empty;
// CHeck
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection(dbConn))
{
// Error Handling
try { conn.Open(); }
catch (Exception ex) { throw ex; }
SqlCommand cmd = new SqlCommand(spddl, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
// Error Handling
try { da.Fill(ds); }
catch (Exception ex) { throw ex; }
Date_CBL.DataSource = ds.Tables[0];
Date_CBL.DataTextField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataValueField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataBind();
// Must Check From Code Behind since you are using it to before Page_Load.. Javascript will work after your Page Show Everything
Date_CBL.Items[1].Selected = true; // Check 2nd Item
BindGridView(conn);
conn.Close();
}
}
}
private void BindGridView(SqlConnection conn)
{
string spretrieve = string.Empty;
string selectedDATE = String.Empty;
using (SqlCommand cmd = new SqlCommand(spretrieve, conn))
{
//Bind selected CheckBoxList items into one string and pass into stored procedure as parameter
// This Will be wrong if you use selected Value
if (Date_CBL.Items[0].Selected == true)
{
selectedDATE = "DATA_DATE";
}
else
{
foreach (ListItem item in Date_CBL.Items)
{
if (item.Selected)
{
DateTime dtTemp = Convert.ToDateTime(item.Value);
selectedDATE += "'" + dtTemp.ToString("yyyy-MM-dd") + "',";
}
}
selectedDATE = selectedDATE.TrimEnd(','); // Don't use substring cause last length is the comma u can use trimEnd
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#DATE", SqlDbType.VarChar).Value = selectedDATE;
string query = cmd.CommandText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try { da.Fill(ds); }
catch (Exception ex) { throw ex; }
Gridview1.DataSource = ds.Tables[0];
Gridview1.DataBind();
}
}
$(function () {
var $all = $("#Date_CBL ").find(":checkbox");
var $first = $all.eq(1);
$first.prop("checked", true);
});

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources