Hide image control from Modal Popup if there is no image based on DataList record using jQuery Ajax in ASP.Net

Last Reply on May 18, 2017 08:56 AM By dharmendr

Posted on May 18, 2017 08:52 AM

I have this image in modal and i want to make it hidden if image is empty, i can do that in formview but this image is displayed without formview

<div class="modal fade" id="myModal1" 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="H1">
                        Pass To Followers</h4>
            </div>
            <div class="modal-header">
                <textarea name="comments" rows="1" cols="20" id="comments" class=" form-control"
                    placeholder="Comment"></textarea>
            </div>
            <div id="modal1body" class="modal-body">
                <div class="tblCustomer">
                    <div>
                        <div class="pull-left " style="margin-top: 2px">
                            <span><span class="name" style="font-family: Arial, Helvetica, sans-serif; font-weight: bold">
                                <%# Eval("fName") %></span>
                                <asp:image id="Image1" runat="server" imageurl='<%# String.Format("PROFILEPHOTOS/{0}",Eval("FImageName").ToString()) %>'
                                    class="image media-object img-rounded animated fadeInDown" style="width: 45px;
                                    height: 45px;" />
                            </span><b /><span class="friendusername">
                                <%# Eval("FriendUserName") %></span><br />
                            <span class="sharepostdate" style="font-family: Arial, Helvetica, sans-serif; font-weight: normal;
                                color: #C0C0C0">
                                <%#  Eval("SharePostDate").ToString().Substring(0,180)+"...(Read More)"%></span><br />
                        </div>
                        <div class="clearfix">
                        </div>
                        <div class="" style="margin-bottom: 4px">
                        </div>
                        <span class="sharecontent" style="font-family: Arial, Helvetica, sans-serif; font-weight: normal">
                            <%# Eval("ShareContent") %></span>
                        <div class="clearfix">
                        </div>
                        <span>
                            <asp:image id="Image2" runat="server" imageurl='<%# String.Format("UserImage/{0}",Eval("ShareImageName").ToString()) %>'
                                class="image2 media-object img-rounded animated fadeInDown" style="width: 30%;
                                height: 30%;" />
                        </span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <span>
                    <asp:linkbutton id="LinkButton9" runat="server" cssclass="btn btn-primary ">
                                            <div class="">
                                                 <asp:Label ID="Label27" runat="server" Text="" CssClass="glyphicon glyphicon-share-alt"></asp:Label>
                                                 <asp:Label ID="Label26" runat="server" Text="Pass Now"></asp:Label>
                                            </div>
                                           
                                           
                                        </asp:linkbutton>
                </span>
            </div>
        </div>
    </div>
</div>
Posted on May 18, 2017 08:56 AM Modified on one year ago

Hi micah,

Refer the below sample. For 1st item in DataList item i have no image. So the photo div is hidden.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <!-- 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);
                if (this.Image != '') {
                    $(".image", table).closest('div').show();
                    $(".image", table).attr("src", this.Image);
                }
                else {
                    $(".image", table).closest('div').hide();
                }
                $(".modal-body").append(table);
                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-sm" />
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:DataList>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div class="container">
        <div class="row">
            <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">
                                    <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 />
                                                <div>
                                                    <b>Photo: </b>
                                                    <img class="image" src='<%# Eval("Image")%>' style='border: 1px solid Red' /><br />
                                                </div>
                                            </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();
    }
}

[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.Trim() + "'"))
        {
            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().Trim(),
                    City = sdr["City"].ToString().Trim(),
                    PostalCode = sdr["PostalCode"].ToString().Trim(),
                    Country = sdr["Country"].ToString().Trim(),
                    Phone = sdr["Phone"].ToString().Trim(),
                    Fax = sdr["Fax"].ToString().Trim(),
                    Image = System.IO.File.Exists(HttpContext.Current.Server.MapPath("Images/" + sdr["ContactName"].ToString().Trim() + ".jpg"))
                    ? "Images/" + sdr["ContactName"].ToString().Trim() + ".jpg" : "",
                });
            }
            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; }
    public string Image { get; set; }
}

Screenshot