Quantcast
Channel: ASP.NET AJAX + Ajax Control Toolkit (ACT)
Viewing all 5678 articles
Browse latest View live

2 radgrids and rsweb:reportviewer export to pdf

$
0
0

I have a web page that has 2 telerik radgrids and a rsweb:reportviewer... and need to export all to pdf.  I can open a print window with window.open() that has all the contgrols rendered .. I need a way to click on a export to pdf button to create a pdf of the same.  I can export the 2 radgrids together to a pdf but run into trouble trying add the reportviewer.  What is the best and cheapest way to create a pdf from these objects that esseence has the same output as the window.open() which uses a div id element to mark the portion of the page to be used with window.open.  high cost of license for a commercial web page.. I bassically only need to render the posrion of teh page with the above objexts to a pdf which can be prompted to open or "save as"... page has vb.net code behind

I have tried radeditor but can not have nested divs which I have to id the portion of page to be used in windows.open()

itextsharp isnt feasible due to the

Thank you in advance for any help


Error when using an AJAX Calendar Extender in UpdatePanel

$
0
0

On my webpage, i have an UpdatePanel that contains an asp:panel Panel and some controls with an Ajax CalendarExtender.  The Panel initially has visibility set to false.  When i select a value from a dropdown, a GridView loads and if the number of rows in the gridview are greater than 0, i set the panel visibility property to true and call the Update method on the UpdatePanel.  When I do this, I receive the following js error:

0x800a139e - JavaScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Extender control 'tbIDMdate_CalendarExtender' is not a registered extender control. Extender controls must be registered using RegisterExtenderControl() before calling RegisterScriptDescriptors().
Parameter name: extenderControl

I have done a bunch of research and so far nothing has worked.  I'm not sure what to do to get it to work, the error appears when I try to set the visibility property of the Panel to True.  My toolscriptmanager is located in the master page.

<asp:UpdatePanelID="updPnlAssignDeliveryMethods"UpdateMode="Conditional"runat="server">
                               
<ContentTemplate>
                                   
<asp:PanelID="pnlAssignDeliveryMethods"runat="server"Visible="false">
                                       
<asp:LabelID="Label18"runat="server"Text="IDM Date:"></asp:Label>
                                       
<asp:TextBoxID="tbIDMdate"runat="server"Width="75px"></asp:TextBox>
                                           
<ajaxToolkit:CalendarExtenderID="tbIDMdate_CalendarExtender"runat="server"Enabled="True"TargetControlID="tbIDMdate">
                                           
</ajaxToolkit:CalendarExtender>
                                       
<asp:LabelID="Label19"runat="server"Text="Delivery Method:"></asp:Label>
                                       
<asp:ButtonID="btnAssignSD"runat="server"CssClass="buttonBlue"OnClick="btnAssignSD_Click"Text="Seat Delivery"/>
                                        &nbsp;
<asp:ButtonID="btnAssignSelfDeploy"runat="server"CssClass="buttonBlue"OnClick="btnAssignSelfDeploy_Click"Text="Self Deploy"/>
                                        &nbsp;
<asp:ButtonID="btnAssignFS"runat="server"CssClass="buttonBlue"OnClick="btnAssignFS_Click"Text="Field Services"/>
                           
                                   
</asp:Panel>
                               
</ContentTemplate>
                           
</asp:UpdatePanel>

 

   

Problem in retaining text of button on partial postback

$
0
0

I have  templatefields that contain buttons in my gridview which is inside an update panel. Following is the aspx definition

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="10000">
</asp:Timer>
<div id="grid-view-container2">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" OnRowCommand="GridView2_RowCommand" OnRowUpdating="GridView2_RowUpdating">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:templatefield HeaderStyle-HorizontalAlign="Center" headertext="Time">
<ItemStyle HorizontalAlign="Center" />
<itemtemplate>
<asp:Label ID="lbltime" runat="server" Text='<%#Eval("Time") %>'></asp:Label>
</itemtemplate>
</asp:templatefield>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="button1" runat="server" CausesValidation="false" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CommandName="show" Font-Bold="true" EnableViewState="true" OnClick="button1_click" Text="Hide" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:Button ID="button2" runat="server" CausesValidation="false" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CommandName="update" Enabled="false" EnableViewState="true" Font-Bold="true" OnClick="button2_click" Text="Update" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="Tan" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<SortedAscendingCellStyle BackColor="#FAFAE7" />
<SortedAscendingHeaderStyle BackColor="#DAC09E" />
<SortedDescendingCellStyle BackColor="#E1DB9C" />
<SortedDescendingHeaderStyle BackColor="#C2A47B" />
</asp:GridView>
</div>
</ContentTemplate> 
</asp:UpdatePanel>

in my code behind file i am changing text of buttons when clicked as follows

protected void button1_click(object sender, EventArgs e)
{
flag = 0;
}
protected void button2_click(object sender, EventArgs e)
{
flag = 1;
}
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (flag == 0)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView2.Rows[index];
Button b1 = (Button)row.Cells[1].FindControl("button1");
Button b2 = (Button)row.Cells[2].FindControl("button2");
if (b1.Text == "Show")
{
b2.Enabled = true;
b1.Text = "Hide"; 
Label lb = (Label)row.Cells[3].FindControl("lblid");
int ID = int.Parse(lb.Text);
foreach (GridViewRow gr in GridView1.Rows)
{
Label lb1 = (Label)gr.Cells[0].FindControl("lblid1");
int id1 = int.Parse(lb1.Text);
if (ID == id1)
{
gr.Visible = true;
}
}

}
else
{
b1.Text = "Show";
b2.Enabled = false; 
Label lb2 = (Label)row.Cells[3].FindControl("lblid");
int id2 = int.Parse(lb2.Text);
foreach (GridViewRow gr1 in GridView1.Rows)
{
Label lb3 = (Label)gr1.Cells[0].FindControl("lblid1");
int id3 = int.Parse(lb3.Text);
if (id2 == id3)
{
gr1.Visible = false;
}

}
}
}
if (flag == 1)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView2.Rows[index];
Button b2 = (Button)row.Cells[2].FindControl("button2");
Button b1 = (Button)row.Cells[1].FindControl("button1");
if(b2.Text=="Update")

Label lb4 = (Label)row.Cells[3].FindControl("lblid");
int ID4 = int.Parse(lb4.Text);
foreach (GridViewRow gr in GridView1.Rows)
{
Label lb5 = (Label)gr.Cells[0].FindControl("lblid1");
int id5 = int.Parse(lb5.Text);
if (ID4 == id5)
{
TextBox tb = (TextBox)gr.Cells[5].FindControl("textbox1");
tb.ReadOnly = false;
}
}
b2.Text = "Submit";
}

else
{
b2.Text = "Update";
Label lb = (Label)row.Cells[3].FindControl("lblid");
int ID = int.Parse(lb.Text);
float Fill_Price;
foreach (GridViewRow gr in GridView1.Rows)
{
Label lb3 = (Label)gr.Cells[0].FindControl("lblid1");
int id3 = int.Parse(lb3.Text);
if (ID == id3)
{
TextBox tb = (TextBox)gr.Cells[5].FindControl("textbox1");
try
{
Fill_Price = float.Parse(tb.Text);
Update_tab(ID, Fill_Price);
getdata1(); 
}
catch
{
Response.Redirect("datapage.aspx");
}
}
}
}
}
}

i have two functions where i bind my grid one for when page is !postback and other when timer's tick occurs

public void getdata2()//for gridview 2
{
con.Open();
SqlCommand cmmd = new SqlCommand("select Time, ID from mytable where Date=(select MAX(Date) from mytable ) order by Time asc ", con);
SqlDataAdapter da2 = new SqlDataAdapter(cmmd);
da2.Fill(ds2, "mytable");
GridView2.DataSource = ds2.Tables["mytable"];
GridView2.DataBind();
ViewState["myvs1"] = GridView2.DataSource;
SqlCommand cmmd2 = new SqlCommand("SELECT MAX(ID) FROM mytable;", con);
a = (Int32)cmmd2.ExecuteScalar();
ViewState["myvs2"] = a;
con.Close();
}

public void onrefresh_gv2()
{
try
{
con.Open();
int a = (int)ViewState["myvs2"];
SqlCommand cmmd = new SqlCommand("select Time, ID from mytable where ID >"+ a + "order by Time asc", con);
SqlDataAdapter dta = new SqlDataAdapter(cmmd);
dta.Fill(ds2, "mytable2");
DataTable d2=ds2.Tables["mytable2"];
mydt = (DataTable)ViewState["myvs1"];
d2.Merge(mydt);//ds2.Tables["mytable2"].Merge(mydt);
GridView2.DataSource = d2;//ds2.Tables["mytable2"];
GridView2.DataBind();
SqlCommand cmmd2 = new SqlCommand("SELECT MAX(ID) FROM mytable;", con);
a = (Int32)cmmd2.ExecuteScalar();
ViewState["myvs1"] = GridView2.DataSource;
ViewState["myvs2"] = a;
}
catch
{
Response.Redirect("datapage.aspx");
}
finally
{
con.Close();
}
}

protected void Timer1_Tick(object sender, EventArgs e)
{
onrefresh_gv2();
}

the problem is that the text of button is not retained on partial postback ( ie on click the text of button1 changes from hide to show which is not retained ) and all buttons come to their initial state when partial postback occurs.

how can i fulfill above task?

Thanks.

Joy

Json result updating the div with full view again

$
0
0

HI,

I am having a view, in that i am displaying html tables with records from db.

I am having one ddl  and a table as follows in the view (not partial view)

script type="text/javascript">$(document).ready(function () {$("#tblbranchdeatails tr:even").css("background-color", "#E6E7E9;");$("#ListofBranchIDss").on("change", function (e) {
            var selected = $(this).children("option:selected").text();
            alert(selected);
            debugger;$.ajax({
                type: "POST",
                data: {
                    value: selected,
                },
                url: "Sources/Sourcess",
                success: function (result) {
                    debugger;
                   // alert(result.data);$("#resultdiv").html(result);
                },
                error:function(res){alert(res.statusText);}
            });

         
        });
        
    });
    </script><html><head><meta name="viewport" content="width=device-width" /><title>Sources</title></head><body style="background-color:#bfd0e4;margin:0 auto;"><table style="width:100%;height:100%;"><tr style="vertical-align:top;"><td style="width:60%"><div id="heading" class="branchheading">SOURCE DETAILS</div><div id="dropdownlist" class="branchidddl"><p>Filter Basedon BranchID:      
                          @Html.DropDownList("ListofBranchIDss", "selectedValue") </p></div><div id="resultdiv"><table   id="tblbranchdeatails" class="clsbranchtable" style="margin-top:5px;"><tr class="tblheadtr">                    <th>
                                    @Html.DisplayNameFor(model => model.SourceTypeID)</th><th>
                                    @Html.DisplayNameFor(model => model.SortOrder)</th><th>
                                    @Html.DisplayNameFor(model => model.BranchID)</th><th style="display:none">
                                    @Html.DisplayNameFor(model => model.IsDisabled)</th><th></th><th></th></tr>
                              @foreach (var item in Model) {<tr><td class="tdclass">
                                    @Html.DisplayFor(modelItem => item.SourceTypeID)</td><td class="tdclass">
                                    @Html.DisplayFor(modelItem => item.SortOrder)</td><td class="tdclass">
                                    @Html.DisplayFor(modelItem => item.BranchID)</td>                                <td class="tdclass">
                                    @Html.ActionLink("Edit", "Edit", new { sourceid = item.SourceID },new { @class = "editSourceDialog"})   </td>
                                 @{  
                                    if (item.IsDisabled==true)  {<td class="lnkenabletd">              
                                        @Html.ActionLink("Enable", "Delete", new { sourceid = item.SourceID,enabledisableflag=false }, new { @class = "lnkenable"})</td>
                                    }
                                else
                                    {<td class="tdclass">
                                        @Html.ActionLink("Disable", "Delete", new { sourceid = item.SourceID,enabledisableflag=true }, new { @class = "lnkdiasbale"})</td>
                                     }
                                }</tr>
                              }</table></div><p class="pstyle">
                        @Html.ActionLink("Create New Source", "Create","Source", new { @class = "addSourceDialog"})        </p><div id="dialog-edit-source" style="display: none;"></div></td><td ><img src="/Images/blue_overlay.jpg"></td><td style="width:30%"><div class="firstlink"> 
                         @Html.ActionLink("Source", "Sources", "Source", new { }, new { @class = "samepagelink" })                  </div><div class="secondlink">                            
                      @Html.ActionLink("Branch ", "Branch", "Branch", new { }, new { @class = "anotherpagelink" })             </div><div class="secondlink"> 
                      @Html.ActionLink("Source Types", "SourceTypes", "SourceType", new { }, new { @class = "anotherpagelink" })                </div><div class="holidayinn"><img src="/Images/holiday_club_logo.png"></div> </td></tr></table></body></html>

I am filtering the html tbl data on change of ddl values using jquery ajax call

Its calling the controller action and returning the model. But the problem is the div is updated with agian the full view not with only the table.So inside div the view is again displaying once again. I need to display only the html table inside div.not the full view.

PLs find my controller action

 [HttpPost]
        public ActionResult Sourcess(string value)
        {
            ModelState.Clear();
            IEnumerable<SourceModel> filtereddata1 = null;
            model = new TrackerModel();           
                model.sourceData = this.ppiService.GetSourceData();
                List<int> branchidlist = new List<int>();
                branchidlist = model.sourceData.Select(x => x.BranchID).Distinct().ToList();
                ViewBag.ListofBranchIDss = branchidlist.Select(x => new SelectListItem() { Text = x.ToString() });

                int branchidtofilter = (value == null || value == string.Empty) ? branchidlist[0] : Convert.ToInt32(value);

                filtereddata1 = (from item in model.sourceData
                                 where item.BranchID == branchidtofilter
                                 select item);

                ViewBag.selectedValue = branchidtofilter;
                return Json(filtereddata1, JsonRequestBehavior.AllowGet);
        }

Pls help me

Thanks in advance

Vidya

ModalPopupExtender Show() not firing

$
0
0

I know this issue has been posted on many different occasions. I've looked so many websites to find a solution to this issue, however none of those solutions have helped me find the correct answer to this.

My code is based on this guy's website >> http://mattberseth.com/blog/2007/07/modalpopupextender_example_for.html

I have a GridView that sources its data from the SqlDataSource1. Within that GridView, in the first column I have View buttons that should show the details of each row in the ModalPopupExtender1. I set its TargetControlID to btnShowPopup, which is not visible but as I say "not visible" doesn't mean it's set Visible="false" but it is set style="display:none" (I found this is the way people do).

The problem is even when I click on one of the View buttons, the ModalPopup doesn't appear. In fact, when I click the button, nothing happens.

On the Visual Basic, I don't see any error messages nor exception handlers after clicking on the View button.

Any help would be appreciated. Thank you in advance!

My code:

<aspx>

<%@ Page Title="" Language="C#" MasterPageFile="~/Main/MasterPage.master" AutoEventWireup="true" CodeFile="SearchAcquisition.aspx.cs" Inherits="PosStock" %><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %><asp:Content ID="Content1" ContentPlaceHolderID="headContent" Runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="Maincontent" Runat="Server"><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager><div class="contentboxh"><h2 class="hpos">Acquisition Search</h2><br /><br /><h2 class="h4" style="text-align: left">Search</h2><br /><asp:TextBox ID="SearchField" runat="server" Width="350px" Height="30px" OnTextChanged="SearchField_TextChanged"></asp:TextBox><asp:Button ID="SearchButton" runat="server" Text="Search" Height="26px" OnClick="SearchButton_Click" BackColor="#7AB800" CssClass="searchbutton" /></div><div class="contentboxh"><asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT [acquisition_ID], [acquisition_name], [acquisition_qty], [acquisition_cost], [acquisition_date], [acquisition_status] FROM [Acquisition] WHERE [acquisition_ID] = @acquisition_ID"
                SelectCommandType="Text" CancelSelectOnNullParameter="true" ConnectionString="<%$ ConnectionStrings:MJENTAConnectionString %>"></asp:SqlDataSource><asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional"><ContentTemplate><asp:GridView ID="GridView1" runat="server" DataKeyNames="acquisition_ID" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true" PageSize="10" Width="95%"><Columns><asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px"><ItemTemplate><asp:Button ID="btnViewDetails" runat="server" Text="Details" CommandName="View" OnClick="BtnViewDetails_Click" /></ItemTemplate></asp:TemplateField><asp:BoundField DataField="acquisition_ID" HeaderText="ID" SortExpression="acquisition_ID" ReadOnly="true" /><asp:BoundField DataField="acquisition_name" HeaderText="Name" SortExpression="acquisition_name" ReadOnly="true" /><asp:BoundField DataField="acquisition_qty" HeaderText="Quantity" SortExpression="acquisition_qty" ReadOnly="true" /><asp:BoundField DataField="acquisition_cost" HeaderText="Cost" SortExpression="acquisition_cost" ReadOnly="true" /><asp:BoundField DataField="acquisition_date" HeaderText="Date Added" SortExpression="acquisition_date" ReadOnly="true" /><asp:BoundField DataField="acquisition_status" HeaderText="Status" SortExpression="acquisition_status" ReadOnly="true" /></Columns></asp:GridView></ContentTemplate></asp:UpdatePanel><asp:Button ID="btnShowPopup" runat="server" style="display:none" /><asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlPopup"
                            CancelControlID="btnClose" BackgroundCssClass="modalBackground" /><asp:Panel ID="pnlPopup" runat="server" CssClass="detail" Width="500px" style="display:none"><asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional"><ContentTemplate><asp:Label ID="lblCustomerDetail" runat="server" Text="Detail" BackColor="LightBlue" Width="95%" /><asp:DetailsView ID="DetailsView1" runat="server" DefaultMode="Edit" Width="95%" BackColor="White" /></ContentTemplate></asp:UpdatePanel><div align="right" style="width:95%"><asp:Button ID="btnSave" runat="server" Text="Save" Width="50px" /><asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" /></div></asp:Panel></div></asp:Content>

<Code behind>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;

public partial class PosStock : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void BtnViewDetails_Click(object sender, EventArgs e)
    {
        Button btnDetails = sender as Button;
        GridViewRow row = (GridViewRow)btnDetails.NamingContainer;

        this.SqlDataSource1.SelectParameters.Clear();
        this.SqlDataSource1.SelectParameters.Add("acquisition_ID", Convert.ToString(this.GridView1.DataKeys[row.RowIndex].Value));
        this.DetailsView1.DataSource = this.SqlDataSource1;
        this.DetailsView1.DataBind();

        this.updPnlCustomerDetail.Update();
        ModalPopupExtender1.Show();

    }
    protected void SearchField_TextChanged(object sender, EventArgs e)
    {

    }
    protected void SearchButton_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MJENTAConnectionString"].ToString());

        SqlCommand cmd;
        
        String str = "SELECT acquisition_ID, acquisition_name, acquisition_qty, acquisition_cost, acquisition_date, acquisition_status FROM Acquisition WHERE (acquisition_name like '%' + @search + '%')";
        cmd = new SqlCommand(str, con);
        cmd.Parameters.Add("@search", SqlDbType.NVarChar).Value = SearchField.Text;
        con.Open();
        cmd.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataSet ds = new DataSet();
        da.Fill(ds, "acquisition_name");
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();
    }
}

Script in a DataList

$
0
0

Hello everybody,

In the ItemTemplate of a DataList, I display a user control that contains an AjaxControlToolkit Slider to input a numeric data.

At the second attempt to modify the value, this makes the page display an exception :

Invalid postback or callback argument.  
Event validation is enabled using <pages enableEventValidation="true"/>
in configuration or <%@ Page EnableEventValidation="true" %>
in a page.
For security purposes, this feature verifies that arguments to
postback or callback events originate from the server control
that originally rendered them. If the data is valid and expected,
use the ClientScriptManager.RegisterForEventValidation method
in order to register the postback or callback data for validation.

As advised in a previous thread, I referred to this page, and inserted this in the page, at the beginning of the Content control :

<script runat="server" >

    string _cbMessage = "";
    // Define method that processes the callbacks on server.
    public void RaiseCallbackEvent(String eventArgument)
    {
        if (DataList1.Controls.Count > 0)
        {
            try
            {
                UserControls_AffichePlat ap = (UserControls_AffichePlat)DataList1.Controls[0].FindControl("AffichePlat1");
                TextBox txb = (TextBox)ap.FindControl("txbCuissonLineaire");
                AjaxControlToolkit.SliderExtender sli = (AjaxControlToolkit.SliderExtender)ap.FindControl("SliderExtender1");
                Page.ClientScript.ValidateEvent(txb.UniqueID, this.ToString());
                Page.ClientScript.ValidateEvent(sli.UniqueID, this.ToString());
                _cbMessage = "Correct event raised callback.";
            }
            catch(Exception ex1)
            {
                _cbMessage = "Error when raising callback : " + ex1.Message;
            }
        }
    }

    // Define method that returns callback result.
    public string GetCallbackResult()
    {
        return _cbMessage;
    }

    protected override void Render(HtmlTextWriter writer)
    {
        if (DataList1.Controls.Count > 0)
        {
            UserControls_AffichePlat ap = (UserControls_AffichePlat)DataList1.Controls[0].FindControl("AffichePlat1");
            TextBox txb = (TextBox)ap.FindControl("txbCuissonLineaire");
            AjaxControlToolkit.SliderExtender sli = (AjaxControlToolkit.SliderExtender)ap.FindControl("SliderExtender1");
            Page.ClientScript.RegisterForEventValidation(sli.UniqueID, this.ToString());
            Page.ClientScript.RegisterForEventValidation(txb.UniqueID, this.ToString());
        }
        base.Render(writer);
    }</script><script type="text/javascript">
    var value1 = new Date();

    function ReceiveServerData(arg, context)
    {
        alert('ReceiveServerData');
        Message.innerText = arg;
        Label1.innerText = "Callback completed at " + value1;
        value1 = new Date();
    }
    function ProcessCallBackError(arg, context)
    {
        alert('ProcessCallBackError');
        Message.innerText = "An error has occurred.";
    }</script>

and that in the code behind :

    private List<PlatPourCommande> lst = new List<PlatPourCommande>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            this.dnlCategorie.SelectedValue = "4";

            using (SqlConnection cnx = new SqlConnection(ConfigurationManager.ConnectionStrings["DataConnectionString"].ConnectionString))
            {
                while (cnx.State == ConnectionState.Closed)
                {
                    try
                    {
                        cnx.Open();
                    }
                    catch
                    {
                    }
                }
                using (SqlCommand cmd = new SqlCommand("SELECT id FROM Plat WHERE idCategorie=4", cnx))
                {
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        PlatPourCommande p = new PlatPourCommande(reader.GetInt32(0));
                        lst.Add(p);
                    }
                    reader.Close();
                }
                cnx.Close();
            }
            ClientScriptManager cs = Page.ClientScript;
            String cbReference = cs.GetCallbackEventReference("'" +
                Page.UniqueID + "'", "arg", "ReceiveServerData", "","ProcessCallBackError", false);
            String callbackScript = "function CallTheServer(arg, context) {" +
                cbReference + "; }";
            cs.RegisterClientScriptBlock(this.GetType(), "CallTheServer",
                callbackScript, true);

            DataList1.DataSource = lst;
            dtbc(DataList1);
        }
    }

dtbc and dtbs are for DataBind(), with exception management.

RaiseCallbackEvent is executed, but I am afraid :

  • ReceiveServerData and ProcessCallbackError never display the alert
  • the page still displays the same exception at the second attempt to modify the value with the slider.

Any idea of what I made wrong ?

Ajax client-side framework failed to load after file selection in Asyncfileupload control

$
0
0

Now before you all start pasting in links to other posts that contain the phrase "Ajax client-side framework failed to load" (and are not helpful in anyway), read below.

There are two (2) Asyncfileupload controls on this page (one works and the other does not).

  • One is in the FooterTemplate of a GridView that is in the InsertItemTemplate of FormView1
  • The other is in the FooterTemplate of a GridView that is in the EditItemTemplate of FormView1
  1. The Asyncfileupload in the InsertItemTemplate works fine. 'Choose File' is clicked, a file is selected and OK is then clicked ........... the control does what ever it does to store the file path in memory or whatever it does (i have no events of my own triggering at this time) and the control background turns green.
  2. The Asyncfileupload in the EditItemTemplate does not work at all (it use to). 'Choose File' is clicked, a file is selected and OK is then clicked ........... the control does what ever it does to store the file path in memory or whatever it does (i have no events of my own triggering at this time) and then the controls background turns red and throws up useless errors.
    • In Chrome:
      • Unknown, server error
    • In IE: 
      • Unknown, server error
      • Ajax client-side framework failed to load

I have looked at the differences in the two and have even reduced the one in the EditItemTemplate to just the Asyncfileupload but it still errors.

I have a couple other pages set up the exact same way, Asyncfileupload in the FooterTemplate of a GridView, inside an InsertItemTemplate and an EditItemTemplate of a FormView.

My only other option is to start the page over from scratch (2,200 lines in the cs and 2,600 in aspx), which is an option I would prefer to avoid.

Thanks for any thoughts you might have.

pagemethods returns html string (from masterpage?)

$
0
0

Hi,

I have managed to set up a call to a function in codebehind through pagemethods. It return a success but instead of the test string (Hello) it returns a html string that seems to be a small part of the masterpage. What am I missing/doing wrong?

    function ShowCurrentTime() {
            PageMethods.Hello(Success, Failure);
    }

    function Success(result) {
        alert(result);
    }
    function Failure(error) {
        alert(error);
    }

code behind:

<WebMethod()>
    Public Shared Function Hello() As String
        Dim SayHello As String = "Hello"
        Return SayHello
    End Function

Thanks in advance,

Pascal


Positioning PopupControlExtender control

$
0
0

Hello,

I am attempting to center the position of a Ajax Popup control but having some difficulty. I've tried changing the OffSet properties of the Ajax PopupControlExtender via JavaScript but to no avail. Here's sample of the code:

// JavaScript
// center popup control                
        var left = (screen.width / 2) - (iWidth / 2);
        var top = (screen.height / 2) - (iHeight / 2);$find('NonModalPopup').OffsetX = Math.round(left);$find('NonModalPopup').OffsetY = Math.round(top);


//HTML
<cc1:PopupControlExtender ID="HorizontalMenu_PopupControlExtender" 
        runat="server" BehaviorID="NonModalPopup" DynamicServicePath="" Enabled="True" 
        ExtenderControlID="" TargetControlID="AccessKeyPanel" 
        PopupControlID="PanelNonModal" ></cc1:PopupControlExtender><asp:Panel ID="PanelNonModal" runat="server" CssClass="modalPopup" 
        style="display:none;"   BackColor="Control" 
        BorderStyle="Ridge" BorderWidth="3px"><div class="header" runat="server" id="divMasterPageTitleBar">            
         TBD   <a onclick="AjaxControlToolkit.PopupControlBehavior.__VisiblePopup.hidePopup(); return false;" title="Close" class="closeDialog" id="ALink_NonModal">X</a></div><iframe id="IFrameNonModal" src="" runat="server"></iframe><div class="footer" style="display:none"><input id="btnOk_nonModal" type="button" value="Done" /><input id="btnCancel_nonModal" type="button" value="Cancel" /></div></asp:Panel>

Any help is appreciated.

AJAX AutoComplete not firing

$
0
0

In my code I have an AJAX AutoComplete, looks like this:

 

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><ajaxToolkit:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" DelimiterCharacters="" Enabled="True" ServicePath="AutoComplete.asmx" ServiceMethod="GetCompletionList" TargetControlID="TextBox1" CompletionSetCount="10" MinimumPrefixLength="2"></ajaxToolkit:AutoCompleteExtender>

Its fairly straight forward and I have done this kind of thing connecting the Web Service from SQL, however this time within the Web Service I wont to connect to a array from strings. The strings will be the network ID's. The web service looks like:

 

Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

Public Class WebService2
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As List(Of String)

        Dim ctx As New PrincipalContext(ContextType.Domain)

        Dim group As GroupPrincipal = GroupPrincipal.FindByIdentity(ctx, "####")
        ' Create a list of strings.
        Dim list As New List(Of String)
        ' if found....
        If group IsNot Nothing Then
            ' iterate over members            
            For Each p As Principal In group.GetMembers()
                list.Add(p.SamAccountName)
            Next
        End If

        list.Sort()

        Return list
    End Function

 

I could chuck the lot into a database beforehand but wouldn't mind trying to solve the problem in the first instance. Anyone got any suggestions?...

:)

GetPostBackEventReference and UpdatePanel - workaround

$
0
0

Hi all,

I had a problem with partial updates of UpdatePanel when calling postback using GetPostBackEventReference method. I saw several posts here regarding this problem with no solution. After some hours of digging into this problem I found a solution and I want to share it with you.

I created sample web site, which you can download here: http://home.karneval.cz/0203398301/AjaxTest.zip

 

Hope this will help you [;)]

 Igor

ajax updateprogress

$
0
0

Hi All,

  I have the following code on my page, but I don't see the wheel spinning when I try to run the application.

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title></head><body><form id="form1" runat="server"><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager><div><center> History table</center> </div><div><asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="pannel"><ProgressTemplate><div id="dvProgress" runat="server" style="position: absolute; top: 300px; left: 550px;
                                    text-align: center;"></div>
                                Please wait to retrieve data...</ProgressTemplate></asp:UpdateProgress></div><div><asp:Image ID="Image2" runat="server" Height="46px" Width="47px" 
                                        ImageUrl="~/Images/25-1.gif" /><asp:GridView ID="GrdHistory" runat="server" AutoGenerateColumns="False" CellPadding="4"
            AllowSorting="True" CssClass="labelBoldx"  ShowFooter="True" Font-Size="Small"
            ForeColor="Black" 
            AllowPaging="false"   HeaderStyle-BackColor="#999999"    ><Columns></Columns></asp:GridView></div></form></body></html>

I didn't write the grid columns, but this grid takes too much time to load. I want that spinning wheel to display, but it doesn't display at all.

any help will be appreciated.

Using Inside an UpdatePanel

$
0
0
Hi, everyone!

We use a service called FormStack and they allow great form functionality along with many ways to embed a form into a page.

A few of the embedding methods creates the form wishing the page DOM or you can paste the full form into your markup.

Using these methods causes a couple of issues with ASP, namely because the form used a Submit button triggering the page to postback.

This got me thinking: could I wrap FormStack's HTML form in an UpdatePanel? That would then create the form's submit button as a trigger for the panel causing partial page postback, no?

This would then solve any ViewState issues caused by embedding the form within the ASPX template, I think.

Does anyone have any experience with something like this? If so, can you please offer any advise?

Thanks!

-Eric

how to make a Mutually Exclusive CheckBox, Compulsory

$
0
0

Hi all

Is it possible to make a Mutually Exclusive CheckBox, Compulsory?  If so what do I need to use as I can't see how the  required Field Validator would work on the below?  

<asp:CheckBox ID="chkBoxBPYes" runat="server" Text="Yes" /><cc1:MutuallyExclusiveCheckBoxExtender ID="cboBPYesExtender" runat="server" 
      Enabled="True" Key="benefitProtectionChoice" TargetControlID="chkBoxBPYes"></cc1:MutuallyExclusiveCheckBoxExtender><asp:CheckBox ID="chkBoxBPNo" runat="server" Text="No" /><cc1:MutuallyExclusiveCheckBoxExtender ID="cboBPNoExtender" runat="server" 
      Enabled="True" Key="benefitProtectionChoice" TargetControlID="chkBoxBPNo"></cc1:MutuallyExclusiveCheckBoxExtender>

htmleditorextender disable image selection

$
0
0

Hi,

I would like to know if there a way to disable image modification and also selection in htmleditorextender ?

I could find a solution to not remove "width" attributes with modification and rebuild AjaxControlToolKit solution.

Thanks.


How to call Server method from JavaScript.

$
0
0

Hi,

   Is there any way to invoke server function from javascirpt method ?
eg: i need to call GetTime() from javascript and assign value to var. 

Function

JQuery AJAX calls not working on live

$
0
0

Hello guys,

JQuery AJAX is giving me a huge headache... Everything works fine on my local machine and used to work fine on the deployment server as well. Since yesterday it's not working anymore and I have no idea why....

For some reason I'm getting a 404 error. 

Does anybody know why this could occur? 

Javascript code:

$.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/LocalServices/Admin.svc/ProductQuery",
                dataType: "json",
                cache: false,
                data: {},
                timeout: 100000,
                success: function (obj) {
                    if (handleError(obj)) {
                        drawProducts(obj.d.Products);
                    }
                },
                error: function (xhr) {
                    if (xhr.responseText) {$("body").html(xhr.responseText);
                    }
                    else
                        alert('TimeOut');
                    return;
                }
            });

WebConfig:

<?xml version="1.0" encoding="utf-8"?><!--
  Weitere Informationen zur Konfiguration der ASP.NET-Anwendung finden Sie unter"http://go.microsoft.com/fwlink/?LinkId=169433".
  --><configuration><configSections><section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections><connectionStrings><add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" /></connectionStrings><system.web><customErrors mode="Off" /><compilation debug="true" targetFramework="4.5.1" /><membership><providers><clear /><add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /></providers></membership><profile><providers><clear /><add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" /></providers></profile><roleManager enabled="false"><providers><clear /><add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /><add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /></providers></roleManager><!--Limit fileupload to 100 Megabyte--><httpRuntime maxRequestLength="102400" /><sessionState timeout="120"></sessionState><pages controlRenderingCompatibilityVersion="4.0" /></system.web><system.webServer><modules runAllManagedModulesForAllRequests="true"></modules><httpErrors errorMode="Detailed" /></system.webServer><entityFramework><defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /><providers><provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /></providers></entityFramework><system.serviceModel><serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="0" /><behaviors><serviceBehaviors><behavior name=""><serviceMetadata httpGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="true" /></behavior></serviceBehaviors></behaviors></system.serviceModel></configuration>

Method:

 public Entities.AjaxResult ProductQuery()
        {
            return Core.Admin.AdminMethods.ProductQuery();
        }

Error:

Javascript Only Runs When TabContainer is Set to OnDemand="False"

$
0
0

ASP.Net 4.5.  Visual Studio 2012.  IE 11.  Latest (final Ajax Toolkit release).

I have javascripting that ensures that ListBox controls return to the selected item upon page refresh (instead of scrolling back to the top of the list).  I have placed this code right at the end of the <ContentTemplate> section of a TabPanel (as seen below).  This code runs only if the TabControl is set to OnDemand="False."  I placed an alert('Got here'); at the top of the code to test.  The alert does NOT fire when OnDemand="True."  I want to use OnDemand="True."  Can anyone help me figure out what is needed to make this work?  Thanks for the help.

<script type="text/javascript">
                    try {
                        var e = document.getElementById("<%= SelectedChaplains.ClientID %>");
                        e.options[e.selectedIndex].selected = true;
                    }
                    catch (Error) {
                    }
                    try {
                        var e = document.getElementById("<%= RDSelection.ClientID %>");
                        e.options[e.selectedIndex].selected = true;
                    }
                    catch (Error) {
                    }
                    try {
                        var e = document.getElementById("<%= SelectedJurisdictions.ClientID %>");
                 e.options[e.selectedIndex].selected = true;
                    }
                    catch (Error) {
                    }</script></ContentTemplate></cc1:TabPanel>

How to register PostBackTriggers in a GridView nested within an UpdatePanel?

$
0
0

I have the following UpdatePanel code:

<asp:UpdatePanel ID="MyUpdatePanel" runat="server" UpdateMode="Conditional"><ContentTemplate><asp:PlaceHolder ID = "MyPlaceHolder" runat = "server"><asp:GridView runat = "server" ID = "MyGridView" DataKeyNames = "ID, Name" AutoGenerateColumns = "false" ShowHeader = "true" GridLines = "None" OnRowDeleting = "Delete" OnRowEditing = "Rename"><Columns><asp:TemplateField><ItemTemplate><asp:ImageButton ID = "RenameButton" Width="15" Height="15" rel="tooltip" data-toggle="tooltip" title="Rename" runat = "server" OnClick = "Rename"/><asp:ImageButton ID = "ExportButton" Width="15" Height="15" rel="tooltip" data-toggle="tooltip" title="Export" runat = "server" OnClick = "Export"/><asp:ImageButton ID = "DeleteButton" Width="15" Height="15" rel="tooltip" data-toggle="tooltip" title="Delete" runat = "server" OnClick = "Delete" />                       </ItemTemplate></asp:TemplateField></Columns></asp:GridView></asp:PlaceHolder></ContentTemplate><Triggers><asp:PostBackTrigger ControlID = "MyUpdatePanel$ctl02$ExportButton" /></Triggers></asp:UpdatePanel>

What is the proper way to register ExportButton in a fully scalable manner? The code as shown works only when there is 1 row in the Gridview - if the GridView is empty it causes a server error and if there is more than 1 row, only the first ExportButton is registered.

ajax auto-complete return values

$
0
0

Hi, 

I am using following code return two values while using ajax autocomplete  but I  want to return 4 values please help me my code as follows.

----default.aspx

function ClientItemSelected(sender, e) {
$get("<%=hfCustomerId.ClientID %>").value = e.get_value();
}
</script>

<System.Web.Script.Services.ScriptMethod(), _
System.Web.Services.WebMethod()> _
Public Shared Function SearchCustomers(ByVal prefixText As String, ByVal count As Integer) As List(Of String)
Dim conn As SqlConnection = New SqlConnection
conn.ConnectionString = ConfigurationManager.ConnectionStrings("SQLConnection").ConnectionString
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "select CustomerId, ContactName from Customers where" & _
" ContactName like @SearchText + '%'"
cmd.Parameters.AddWithValue("@SearchText", prefixText)
cmd.Connection = conn
conn.Open()
Dim customers As List(Of String) = New List(Of String)
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
Dim item As String = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(sdr("ContactName").ToString, sdr("CustomerId").ToString)
customers.Add(item)
End While
conn.Close()
Return customers
End Function

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
 
TextBox1.Text = Request.Form(hfCustomerId.UniqueID)
TextBox2.Text = Request.Form(txtCustomer.UniqueID)
End Sub

Viewing all 5678 articles
Browse latest View live




Latest Images