Display data from DataList into Model Popup using jQuery Ajax in ASP.Net

Last Reply on May 11, 2017 03:28 AM By dharmendr

Posted on May 07, 2017 11:50 PM

i want a version of this code below on juery, like calling a data in datalist to formview on model instead of using post back server method . SCRIPT

<script type='text/javascript'>
    function openModal9t() {
        $('#myModal9t').modal('show');
    }
    function openModalComments() {
        $('#mycomments').modal('show');
    }
</script>

--------------------------------------- code

protected void linkonlyPOSTModal_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "myModal9t();", true);
}
-------------------------------------------------------------

protected void btnSUBMTE_Click(object sender, EventArgs e)
{
        string modelId2 = (Post.Row.FindControl("lblModalId") as Label).Text;
        string userName2 = (Post.Row.FindControl("lblUserName") as Label).Text;
        string fuserName2 = (Post.Row.FindControl("lblfUserName") as Label).Text;
        string contentPost2 = (Post.Row.FindControl("lblpost") as Label).Text;
        string comment2 = (Post.Row.FindControl("txtcomment") as TextBox).Text;

        
        string img2 = (Post.Row.FindControl("Image2") as System.Web.UI.WebControls.Image).ImageUrl.Split('/')[(Post.Row.FindControl("Image2") as System.Web.UI.WebControls.Image).ImageUrl.Split('/').Length - 1];
        string imgpostImage2 = (Post.Row.FindControl("postImage") as System.Web.UI.WebControls.Image).ImageUrl.Split('/')[(Post.Row.FindControl("postImage") as System.Web.UI.WebControls.Image).ImageUrl.Split('/').Length - 1];
        string imgImage2 = (Post.Row.FindControl("userImage") as System.Web.UI.WebControls.Image).ImageUrl.Split('/')[(Post.Row.FindControl("userImage") as System.Web.UI.WebControls.Image).ImageUrl.Split('/').Length - 1];
        // string Shimg = (SharePost.Row.FindControl("sharimg") as System.Web.UI.WebControls.Image).ImageUrl.Split('/')[(Post.Row.FindControl("shareimg") as System.Web.UI.WebControls.Image).ImageUrl.Split('/').Length - 1];
        string FRIDeimg2 = (SharePost.Row.FindControl("friIMAGE") as System.Web.UI.WebControls.Image).ImageUrl.Split('/')[(Post.Row.FindControl("friIMAGE") as System.Web.UI.WebControls.Image).ImageUrl.Split('/').Length - 1];
        string fname2 = (SharePost.Row.FindControl("lblfname") as Label).Text;
        DateTime LbPostDate2 = Convert.ToDateTime((Post.Row.FindControl("lbldate") as Label).Text);
        string LabDate2 = (Post.Row.FindControl("nulldate") as Label).Text;
       
       
        string contentpost2 = (Post.Row.FindControl("LabeContent") as Label).Text;
        string shContent2 = (Post.Row.FindControl("lblpost") as Label).Text;
        
        string path02 = (Post.Row.FindControl("lblPATH2") as Label).Text;
        string path42 = (Post.Row.FindControl("lblPATH") as Label).Text;
        string imgeupload2 = (Post.Row.FindControl("lblimageupload") as Label).Text;
       
        InsertDatabase2(userName2, fuserName2, contentPost2, modelId2, comment2, img2, imgpostImage2, imgImage2, contentpost2, 
        FRIDeimg2, fname2, LbPostDate2, shContent2, path42, path02, LabDate2, imgeupload2);
        sb.Append(@"<script type='text/javascript'>");
        sb.Append("$(function () {");
        sb.Append(" $('#myModal9t').modal('hide');});");
        sb.Append("</script>");
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ModelScript", sb.ToString(), false);

}

private void InsertDatabase2(string userName2, string fuserName2, string contentPost2, string modelId2, string 
comment2, string img2, string imgpostImage2, string imgImage2, string contentpost2, string FRIDeimg2, string fname2,
 DateTime LbPostDate2, string shContent2, string path42, string path02, string LabDate2, string imgeupload2)
{
        using (SqlConnection con = new SqlConnection(constrr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO USERPost VALUES(@UserName,@FriendUserName,@fName,
@Content,@Id,@TodayDate,@PostDate,@Comments,@FImageName,@ShImageName,@ContentPost,@SendDate,@ImageName1,@TotalCount,@Path,@ShPath)", con))
            {
                // cmd.Parameters.AddWithValue("@sId", modelId);
                cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
                cmd.Parameters.AddWithValue("@FriendUserName", userName2);
                cmd.Parameters.AddWithValue("@fName", fname2);
                cmd.Parameters.AddWithValue("@Content", shContent2);
                cmd.Parameters.AddWithValue("@Id", modelId2);
                cmd.Parameters.AddWithValue("@TodayDate", LabDate2);
                cmd.Parameters.AddWithValue("@PostDate", LbPostDate2);
                cmd.Parameters.AddWithValue("@Comments", comment2);
                cmd.Parameters.AddWithValue("@FImageName", imgImage2);
                cmd.Parameters.AddWithValue("@ShImageName", imgpostImage2);
                cmd.Parameters.AddWithValue("@ContentPost", contentpost2);

                cmd.Parameters.AddWithValue("@SendDate", DateTime.Now);
                cmd.Parameters.AddWithValue("@ImageName1", imgeupload2);

                cmd.Parameters.AddWithValue("@TotalCount", 1);
                cmd.Parameters.AddWithValue("@Path", path02);
                cmd.Parameters.AddWithValue("@ShPath", path42);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                //  Response.Redirect("Home.aspx");
                string message = "Post Passed successfully.";
                string script = "window.onload = function(){ alert('";
                script += message;
                script += "')};";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
            }
        }
        this.Populatebooks();
}
Results 1 - 5 of 9 12
Posted on May 07, 2017 11:50 PM
Hi @micah,
Please try the following

Drag and Drop Items of DataList using jQuery Draggable Plugin in ASP.Net

It might help you.

Cheers Andrea.

Posted on May 08, 2017 12:33 AM

Hi Please you directed me to drag and drop solution . not what my question says. I just need the jquery version of the code in my question . I don't like the post back method that loads the entire page when the data is click to display on model .


Posted on May 08, 2017 01:12 AM

i tried this simple approach but cant finish it

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"
        rel="stylesheet" />
    <script type="text/javascript">
        function Showalert() {
            document.getElementById("testbutton").click();
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:DataList ID="dlstProducts" runat="server" RepeatColumns="3" CellSpacing="10"
            RepeatDirection="Horizontal" RepeatLayout="Table" OnEditCommand="dlstProducts_EditCommand" OnItemCommand="dlstProducts_ItemCommand">
            <ItemTemplate>
                <td>
                    <asp:Label ID="ProdID" runat="server" Text='<%#Eval("Id") %>' /><br />
                </td>
                <asp:Button CommandName="Testcom" ID="Button1" runat="server" Text="Button" />
            </ItemTemplate>
        </asp:DataList>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div class="container">
            <div class="row">
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
                <div aria-hidden="true">
                    <button id="testbutton" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
                        Launch modal
                    </button>
                </div>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                        <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
                        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                            aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span></button>
                                        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                                    </div>
                                    <div class="modal-body">
                                        <asp:TextBox ID="TextBox1" runat="server" placeholder="First Name" class="form-control"></asp:TextBox><br />
                                        <asp:TextBox ID="TextBox2" runat="server" placeholder="Middle Name" class="form-control"></asp:TextBox><br />
                                        <asp:TextBox ID="TextBox3" runat="server" placeholder="Last Name" class="form-control"></asp:TextBox><br />
                                    </div>
                                    <div class="modal-footer">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br />
                        <br />
                        <br />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </div>
    </form>
</body>
</html>

code

 

 protected void Page_Load(object sender, EventArgs e)
        {
private void Populatebooks()
    {
        // string userId = Session["userName"].ToString();
        // string userId = Session["userName"].ToString();
        //    string str = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
        string Populatebooks = "GetUserPOSTS";
        using (SqlConnection con = new SqlConnection(constring4))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand(Populatebooks, con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                // cmd.Parameters.AddWithValue("@Name", Request.QueryString["Id"].ToString());
                cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
                // cmd.Parameters.AddWithValue("@Id", Id);
                //lblpost.Text = TextBixcomment.Text.Replace(Environment.NewLine, "<BR />");
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                ViewState["DataTable"] = dt;
                dlstProducts.DataSource = dt;
                dlstProducts.DataBind();
            }
        }
    
  protected void dlstProducts_ItemCommand(object source, DataListCommandEventArgs e)
        { 

if (e.CommandName == "Testcom")
            {

//////code remaning 
          ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);

 


Posted on May 08, 2017 07:50 AM Modified on on Oct 24, 2017 06:57 AM

Refer the below sample. There is no need to take formview you can simply show in table format inside modal as form view is also rendered as table also.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        table
        {
            border: 1px solid #ccc;
        }
        table th
        {
            background-color: #F7F7F7;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 5px;
            border-color: #ccc;
        }
    </style>
    <!-- Bootstrap -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript">
        $(function () {
            $('[id*=Button1]').on('click', function () {
                var id = $(this).closest('tr').find($('[id*=lblName]')).text();
                $.ajax({
                    type: "POST",
                    url: "CS.aspx/GetCustomers",
                    data: '{name:"' + id + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    },
                    error: function (response) {
                        alert(response.d);
                    }
                });
                return false;
            });
        });

        function OnSuccess(response) {
            var table = $(".modal-body").find('table').eq(0).clone(true);
            var customers = response.d;
            $(".modal-body").find('table').eq(0).remove();
            $(customers).each(function () {
                $(".name", table).html(this.ContactName);
                $(".city", table).html(this.City);
                $(".postal", table).html(this.PostalCode);
                $(".country", table).html(this.Country);
                $(".phone", table).html(this.Phone);
                $(".fax", table).html(this.Fax);
                $(".modal-body").append(table).append("<br />");
                table = $(".modal-body").find('table').eq(0).clone(true);
            });
            $('#myModal').modal('show');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:DataList ID="dlstProducts" runat="server" RepeatColumns="3" CellSpacing="10"
        RepeatDirection="Horizontal" RepeatLayout="Table">
        <ItemTemplate>
            <table>
                <tr>
                    <td>
                        <b>ID : </b>
                        <asp:Label ID="ProdID" runat="server" Text='<%#Eval("Id") %>' /><br />
                        <b>Name : </b>
                        <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' />
                    </td>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="Show" class="btn btn-primary btn-lg" />
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:DataList>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div class="container">
        <div class="row">
            <%--<div aria-hidden="true">
                <button id="testbutton" type="button" class="btn btn-primary btn-lg" data-toggle="modal"
                    data-target="#myModal">
                    Launch modal
                </button>
            </div>--%>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
                    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                        aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title" id="myModalLabel">
                                        Customer Details</h4>
                                </div>
                                <div align="center" class="modal-body">
                                    <%--<asp:TextBox ID="TextBox1" runat="server" placeholder="First Name" class="form-control"></asp:TextBox><br />
                                    <asp:TextBox ID="TextBox2" runat="server" placeholder="Middle Name" class="form-control"></asp:TextBox><br />
                                    <asp:TextBox ID="TextBox3" runat="server" placeholder="Last Name" class="form-control"></asp:TextBox><br />--%>
                                    <table class="tblCustomer" cellpadding="2" cellspacing="0" border="1">
                                        <tr>
                                            <td>
                                                <b>Name: </b><u><span class="name">
                                                    <%# Eval("ContactName") %></span></u>
                                                <br />
                                                <b>City: </b><span class="city">
                                                    <%# Eval("City") %></span><br />
                                                <b>Postal Code: </b><span class="postal">
                                                    <%# Eval("PostalCode") %></span><br />
                                                <b>Country: </b><span class="country">
                                                    <%# Eval("Country")%></span><br />
                                                <b>Phone: </b><span class="phone">
                                                    <%# Eval("Phone")%></span><br />
                                                <b>Fax: </b><span class="fax">
                                                    <%# Eval("Fax")%></span><br />
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="modal-footer">
                                </div>
                            </div>
                        </div>
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </div>
    </form>
</body>
</html>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "Thomas Hardy", "Ireland");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Ana Trujillo", "France");
        dt.Rows.Add(4, "Antonio Moreno", "Brazil");
        dlstProducts.DataSource = dt;
        dlstProducts.DataBind();
        DataTable dt1 = new DataTable();
    }
}

[WebMethod]
public static List<Customer> GetCustomers(string name)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT ContactName,City,PostalCode,Country,Phone,Fax FROM Customers WHERE ContactName = '" + name + "'"))
        {
            cmd.Connection = con;
            List<Customer> customers = new List<Customer>();
            con.Open();
            SqlDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                customers.Add(new Customer
                {
                    ContactName = sdr["ContactName"].ToString(),
                    City = sdr["City"].ToString(),
                    PostalCode = sdr["PostalCode"].ToString(),
                    Country = sdr["Country"].ToString(),
                    Phone = sdr["Phone"].ToString(),
                    Fax = sdr["Fax"].ToString(),
                });
            }
            con.Close();
            return customers;
        }
    }
}

public class Customer
{
    public string ContactName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
}

Screenshot


Posted on May 08, 2017 08:27 AM

Thank you for responding , Please I was talking of a datalist which when I click a button like show it will pop up that data in formview inside model . Am using procedure to fetch record from database