Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, 25 July 2015

Insert Update Delete in ASP.NET using Jquery (Ajax/Json)

Create table UserList
Use following query to create table:

CREATE TABLE [dbo].[UserList](
       [UserName] [varchar](100) NULL,
       [Password] [varchar](100) NULL
)




Arrange your file in solutions explorer in given below manner.


Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script src="Scripts/Default.js" type="text/javascript"></script>
</head>
<body style="margin:10px">
    <form id="form1" runat="server" autocomplete="off">
    <div>
        <table border="0" class="table-condensed" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            Username:
        </td>
        <td>
            <asp:TextBox ID="txtUsername" runat="server" Text="" />
        </td>
    </tr>
    <tr>
        <td>
            Password:
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button ID="btnSave" CssClass="btn btn-success" Text="Save" runat="server" />
            <asp:Button ID="btnMessage" CssClass="btn btn-info" Text="Load Data" runat="server" />
            <%--<input  type="button" value="click me" onclick="asyncServerCall(1);" />--%>
        </td>
    </tr>
</table>
<hr />
<asp:GridView ID="gvUsers" runat="server" CssClass="table-condensed" HeaderStyle-BackColor="#3AC0F2"
    HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2">
</asp:GridView>
    </div>
    <div>
        <table id="gvUsersTable" style="margin-left:10px;font-family:Courier New" class="table-condensed table-bordered">
           
        </table>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

* Add below namespaces

using System.Web.Services;
using System.Web.Script.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;



 [WebMethod]
        [ScriptMethod]
        public static List<User> getUserData()
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            List<User> details = new List<User>();
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM UserList"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                       
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        sda.Fill(dt);
                        foreach (DataRow dtrow in dt.Rows)
                        {
                            User user = new User();
                            user.Username = dtrow["UserName"].ToString();
                            user.Password = dtrow["Password"].ToString();
                            details.Add(user);
                        }
                    }
                }
            }
            return details;
        }

         
        [WebMethod]
        [ScriptMethod]
        public static void SaveUser(User user)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO UserList VALUES(@Username, @Password)"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Username", user.Username);
                    cmd.Parameters.AddWithValue("@Password", user.Password);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        [WebMethod]
        [ScriptMethod]
        public static void deleteUser(string id)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("delete UserList where UserName=@userName"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@userName", id);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

User.cs

public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

Default.js

/*submit*/

//Save into Database
$(function () {
    $("[id*=btnSave]").bind("click", function () {
        var user = {};
        $(this).attr('disabled', 'disabled');
        $(this).val('Please Wait...');
        user.Username = $("[id*=txtUsername]").val();
        user.Password = $("[id*=txtPassword]").val();
        if (user.Username != "" && user.Password != "") {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveUser",
                data: '{user: ' + JSON.stringify(user) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("User has been added successfully.");
                    $("#gvUsersTable").empty();
                    getUserList();
                    resetForm();
                }
            });
        }
        else {
            alert("Please fill the details !");
            $(this).removeAttr('disabled');
            $(this).val('Save');
        }
        return false;
    });
});

//Reset Form
function resetForm() {
    //After Save
    $("[id*=btnSave]").removeAttr('disabled');
    $("[id*=btnSave]").val("Save");
    $("[id*=txtUsername]").val("");
    $("[id*=txtPassword]").val("");

    //After Load
    $("[id*=btnMessage]").removeAttr('disabled');
    $("[id*=btnMessage]").val("Load Data");
}

//Get grid by Button
$(function () {
    $("[id*=btnMessage]").bind("click", function () {
        $(this).val("Please Wait...");
        $("#gvUsersTable").empty();
        getUserList();

        $(this).attr('disabled', 'disabled');

        return false;
    });
});

//Load grid after window Load
$(document).ready(function () {
    $(window).load(function () {
        getUserList();
    });
});

//Get UserList and bind it into table
function getUserList() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/getUserData",
        data: "{}",
        dataType: "json",
        success: function (data) {
            if (data.d.length > 0) {
                $("#gvUsersTable").append("<tr style='background-color:#3AC0F2'><th>UserName</th> <th>Password</th><th>Delete</th></tr>");
                for (var i = 0; i < data.d.length; i++) {
                    $("#gvUsersTable").append("<tr><td>" + data.d[i].Username + "</td><td>" + data.d[i].Password + "</td><td align='center'>" + "<button style='background-color:#F99292;border:0px none;border-radius:50px' onclick='javascript:deleteUser(this.value);return false;' value='" + data.d[i].Username + "'>&times;</button>" + "</td></tr>");
                }
            }
            resetForm();
        },
        error: function (result) {
            //alert("Error"+result);
        }
    });
}

//delete User from List
function deleteUser(id) {
    if (id == null || id == "") {
        alert("Id not Proper");
    }
    else {
        $.ajax({
            type: "POST",
            url: "Default.aspx/deleteUser",
            data: '{id: ' + JSON.stringify(id) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
               
                $("#gvUsersTable").empty();
                getUserList();
                alert("User has been deleted successfully.");
            }
        });
    }
    return false;
 }

Result



Monday, 6 July 2015

Print / Export SSRS report in ASP.NET | Print Reportviewer Report using JavaScript / Jquery

Create a report from following post 
http://ssrsmegabits.blogspot.in/2015/06/ssrs-report-in-aspnet-example.html

Now we will update above solution for Print SSRS reports using JavaScript and Export it in PDF Format.

Design:

<div id="result"></div>
    <div id="content">
    <input id="btnPrint" type="button" value="Print Report" onclick="PrintReport();" />
    <asp:Button ID="btnExportPDF" runat="server" Text="PDF"
            onclick="btnExportPDF_Click" />
    <rsweb:ReportViewer  Width="100%" ShowToolBar="false" ID="rptvMyReport" runat="server" AsyncRendering="false">
    </rsweb:ReportViewer>

    </div>

Here we have two div with id 'result' and 'content'.
In result div we will copy the content div in the print format and call print method in javascript.
One button added for export report in PDF Format.

javascript Code:

This code for Print ssrs report.

<script type="text/javascript">   
        function PrintReport() {
            var viewerReference = $find('<%=rptvMyReport.ClientID%>');

            $('#result').empty();
            var stillonLoadState = viewerReference.get_isLoading();

            if (!stillonLoadState) {
               
                var reportArea = viewerReference.get_reportAreaContentType();
                if (reportArea == Microsoft.Reporting.WebFormsClient.ReportAreaContent.ReportPage) {
                    $('#rptvMyReport').clone().prependTo("#result");
                    //copy reportviewer report in div
                    $('#content').hide();
                    $('#result').show();
                    //hide reportviewer containing div and show copied div  
                    window.print();
                     //Open Print dialog
                    $('#content').show();
                    $('#result').hide();
                    //Reset 
                }
            }   
        }
     </script>

Now we will added this code in code behind to get SSRS report in PDF Format.

protected void btnExportPDF_Click(object sender, EventArgs e)
        {
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;
            string Title = "UserList " + Convert.ToString(DateTime.Now);
            byte[] bytes = rptvMyReport.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + Title + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush();
        }

Note : If you want to get report in  WORD and EXCEL format then update it as following.

For Excel:
byte[] bytes = rptvMyReport.LocalReport.Render("EXCEL"nullout mimeType, out encoding, out extension, out streamIds, out warnings);

For Word:
byte[] bytes = rptvMyReport.LocalReport.Render("WORD"nullout mimeType, out encoding, out extension, out streamIds, out warnings);


Now check the output, you will get the print and export working in ASP.NET.

Tuesday, 2 June 2015

Open Link in Disabled Window using JavaScript

Below code is to open the link with disabled address bar and toolbar using javascript.

We have window.open() method to get the link in new window and before this we set some attributes to new window in strWindowFeatures.

Also, you can use this code for ASP.NET Hyperlink tag.

Copy this code and  save it as filename.html to get the result.

<html>
<head>
<script>
var windowObjectReference;
var strWindowFeatures="height="+screen.height+",width="+screen.width+",fullscreen=yes,menubar=no,location=no,resizable=no,scrollbars=yes,status=no";

function openRequestedPopup()
{
windowObjectReference=window.open("http://www.google.co.in/","Google",strWindowFeatures);
}
</script>
</head>

<body>
  <form>
    <a href="#" onClick="openRequestedPopup()">Click</a>
  </form>
</body>

</html>