Feb 10, 2017

mvc jquery save

<form action="/Plugin/Ajax/ContactUs" class="form-horizontal" id="contact-form" method="post" name="contact-form"> <div class="col-sm-6">
<div class="form-group">
<div class="col-sm-12">
<input class="validate[required] form-control" id="FullName" name="FullName" placeholder="Name" size="30" type="text" value="" />
<label id="lblName" name="lblName" class="errorlbl"></label>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input class=" validate[required,custom[email]] form-control" id="ContactEmail" name="ContactEmail" placeholder="Email" size="30" type="text" value="" />
<label id="lblEmail" name="lblEmail" class="errorlbl"></label>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input class="validate[required] form-control" id="ContactNumber" name="ContactNumber" placeholder="Mobile" size="30" type="text" value="" />
<label id="lblContactNumber" name="lblContactNumber" class="errorlbl"></label>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<div class="col-sm-12">
<textarea class="validate[required] form-control" cols="20" id="ContactMessage" name="ContactMessage" placeholder="Message" rows="7" width="100%">
</textarea>
<label id="lblContactMessage" name="lblContactMessage" class="errorlbl"></label>
</div>
</div>
<div class="my_contactbtn">
<button id="btnContact" class="btn my_contactsubmit" name="btnFeedback">Submit</button>
<p style="display:inline;"><span id="contact-msg" class=""></span></p>
</div>
</div>
</form>





<script type="text/javascript">
$(function () {
$("#ContactNumber").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 107]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
if ($(this).val().length >= 10) {
return false;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
$(document).ready(function () {
//Header
$("#btnContact").click(function (e) {
e.preventDefault();
if ($("#FullName").val() == '') {
$("#lblName").text("Please fill Full Name");
$("#FullName").focus();
return false;
}
else {
$("#lblName").text("");
}
if ($("#ContactEmail").val() == '') {
$("#lblEmail").text("Please fill Full Name");
$("#ContactEmail").focus();
return false;
}
else {
$("#lblEmail").text("");
}
if ($("#ContactNumber").val() == '') {
$("#lblContactNumber").text("Please fill Full Name");
$("#ContactNumber").focus();
return false;
}
else {
$("#lblContactNumber").text("");
}
if ($("#ContactMessage").val() == '') {
$("#lblContactMessage").text("Please fill Full Name");
$("#ContactMessage").focus();
return false;
}
else {
$("#lblContactMessage").text("");
}
$.ajax({
url: '/Ajax/ContactUs',
data: $('#contact-form').serialize(),
type: 'POST'
})
.done(function (data) {
if (data.IsSuccess) {
$('#contact-msg').html(data.Message).addClass('col-sm-12 control-label success');
$('#contact-form').find("input[type=text], textarea").val("");
}
else {
$('#contact-msg').html(data.Message).addClass('col-sm-12 control-label error');
}
$('#btnContact').val('Submit');
})
.fail(function (err) {
$('#contact-msg').html('Failed To Perform Action. Please Try Again.').addClass('col-sm-12 control-label error');
$('#btnContact').html('Connect');
});
//return false;
});
});
</script>

Code first mvc

https://www.codeproject.com/Articles/826571/Code-First-Approach-with-ASP-NET-MVC-Framework


jquery save & fetch asp.net

Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

    <style type="text/css">

        <style type="text/css">

        body

        {

            font-family: Verdana;

            font-size: 11px;

        }    

        .errMsg

        {

            width: 200px;

            text-align: left;

            color: yellow;

            font: 12px arial;

            background: red;

            padding: 5px;

            display: none;

        }

     

        .tblResult

        {

            border-collapse: collapse;

        }      

        .tblResult td

        {

            padding: 5px;

            border: 1px solid red;

        }      

        .tblResult th

        {

            padding: 5px;

            border: 1px solid red;

        }      

        img

        {

            cursor: pointer;

        }

    </style>

    </style>
</head>
<body>
    <form id="form1" runat="server">

    <div>

    <table cellspacing="0" cellpadding="0">

     <tr>

            <td colspan="2">

                <%--//=== Here we will show error and confirmation messages.--%>

                <div class="errMsg">

                </div>

            </td>

        </tr>

         <tr>

            <td>

                <b>Name</b>

            </td>

            <td>

                <asp:TextBox runat="server" ID="txtName" />

            </td>

        </tr>

        <tr>

            <td>

                <b>Email</b>

            </td>

            <td>

                <asp:TextBox runat="server" ID="txtEmail" />

            </td>

        </tr>

        <tr>

            <td>

                <b>Age</b>

            </td>

            <td>

                <asp:TextBox runat="server" ID="txtAge" />

            </td>

        </tr>

        <tr>

            <td colspan="2">

                <input type="button" onclick="saveData()" id="btnSave" value="Save" title="Save" />

            </td>

        </tr>

         <tr>

            <td colspan="2">

                <%--//==== We will show our data in this div--%>

                <div id="divData">

                </div>

            </td>

        </tr>

    </table>

    </div>

    <script type="text/javascript">

        function clear() {

            $("#txtName").val("");

            $("#txtEmail").val("");

            $("#txtAge").val("");

        }



        function bindData() {



            $.ajax({

                type: "POST",

                url: "Default.aspx/getData",

                data: "{}",

                contentType: "application/json; charset=utf-8",

                datatype: "jsondata",

                async: "true",

                success: function (response) {



                    if ($('#tblResult').length != 0) // remove table if it exists

                    { $("#tblResult").remove(); }



                    var table = "<table class='tblResult' id=tblResult><thead> <tr><th>Name</th><th>Email</th><th>Age</th></thead>  <tbody>";

                    for (var i = 0; i <= response.d.length - 1; i++) {

                        var row = "<tr>";



                        row += '<td>' + response.d[i].Name + '</td>';

                        row += '<td>' + response.d[i].Email + '</td>';

                        row += '<td>' + response.d[i].Age + '</td>';

                        row += '</tr>';

                        table += row;

                    }

                    table += '</tbody></table>';

                    $('#divData').html(table);

                    $("#divData").slideDown("slow");

                },

                error: function (response) {

                    alert(response.status + ' chandan ' + response.statusText);

                }

            });

        }

        function saveData() {

            var txtName = $("#txtName").val();

            var txtEmail = $("#txtEmail").val();

            var txtAge = $("#txtAge").val();

            $.ajax({

                type: "POST",

                url: "Default.aspx/saveData",

                data: "{name:'" + txtName + "',email:'" + txtEmail + "',age:'" + txtAge + "'}",

                contentType: "application/json; charset=utf-8",

                datatype: "jsondata",

                async: "true",

                success: function (response) {

                    $(".errMsg ul").remove();

                    var myObject = eval('(' + response.d + ')');

                    if (myObject > 0) {

                        bindData();

                        $(".errMsg").append("<ul><li>Data saved successfully</li></ul>");

                    }

                    else {

                        $(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");

                    }

                    $(".errMsg").show("slow");

                    clear();

                },

                error: function (response) {

                    alert(response.status + ' ' + response.statusText);

                }

            });

        }

    </script>

    </form>
</body>
</html>


Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]

    public static int saveData(string name, string email, string age)

    {

        try

        {

            int status = 1;

            string Query = string.Empty;

            SqlConnection cn = new SqlConnection("Data Source=WIN-PC\\SQLEXPRESS;Initial Catalog=Json;Integrated Security=True");

            Query = "INSERT INTO Student (Name,Email,Age,CreatedOn) VALUES ('" + name + "','" + email + "','" + age + "',GETDATE())";

            SqlCommand cmd = new SqlCommand(Query, cn);

 

            cn.Open();

            cmd.ExecuteNonQuery();

            cn.Close();

            return status;

        }

      catch

      {

          return -1;

      }

}


[WebMethod]

    public static Student[] getData()

    {

        string data = string.Empty;

        data = "dhdhdhddh";

        StudentCollection sc = new StudentCollection();

        try

        {

            SqlConnection con = new SqlConnection("Data Source=WIN-PC\\SQLEXPRESS;Initial Catalog=Json;Integrated Security=True");

            if (con.State == ConnectionState.Closed)

            {

                con.Open();

            }

            SqlDataReader dr;

            SqlCommand cmd;

            string FetchData = "Select * From Student";

            cmd = new SqlCommand(FetchData, con);

            dr = cmd.ExecuteReader();

          

            if (dr.Read())

            {

                while (dr.Read())

                {

                    Student s = new Student();

                    s.Name = dr[0].ToString();

                    s.Email = dr[1].ToString();

                    s.Age = dr[2].ToString();

                    sc.Add(s);

                }

            }

            return sc.ToArray();

        }

        catch

        {

            return sc.ToArray();

        }

    }

}

 

public class Student

{

    public string Name { get; set; }

    public string Email { get; set; }

    public string Age { get; set; }

}

public class StudentCollection : List<Student>

{

    public void Add(Student st)

    {

        base.Add(st);

    }

}

desktop application connection string

namespace Payroll
{
    class Connection
    {
        private  static SqlConnection SqlCon;

        //private readonly static SqlConnection SqlCon = new SqlConnection("Server=petunia.arvixe.com; database=visiondb; uid=vision1; password=vision2;");

        public static SqlConnection CON
        {
            get
            {
              return   SqlCon = new SqlConnection("Server=WIN-PC\\SQLEXPRESS; database=Payroll;integrated Security=SSPI");
            }
        }
    }
}

Mail Send With Pdf

protected void MailSendWithCoponPdf(string Email,string Coupon)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                string companyName = "xxxxxxxx";
                string orderNo = "#2303";
                StringBuilder sb = new StringBuilder();
                sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
                sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Coupon</b></td></tr>");
                sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>----------------------------------------------------------------</b></td></tr>");
                sb.Append("<tr><td colspan = '4'><center><img src='http://www.xxxxxx.com/images/logo.png' width='100px' height='100px'/></center></td></tr>");
                sb.Append("<tr><td colspan = '4'><b>Coupon No : </b>");
                sb.Append(orderNo);
                sb.Append("</td></tr><tr><td colspan = '4'><b>Date: </b>");
                sb.Append(DateTime.Now);
                sb.Append(" </td></tr>");
                sb.Append("<tr><td colspan = '4'><b>Office Address:</b> </td></tr><td colspan = '4'>");
                sb.Append(companyName);
                sb.Append("</td></tr>");
                sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>----------------------------------------------------------------</b></td></tr>");
                sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'>Please come out at our office with this Coupon</td></tr>");
                sb.Append("</table>");




                StringReader sr = new StringReader(sb.ToString());

                Document pdfDoc = new Document(PageSize.POSTCARD, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                    pdfDoc.Open();
                    htmlparser.Parse(sr);
                    pdfDoc.Close();
                    byte[] bytes = memoryStream.ToArray();
                    memoryStream.Close();



                    ////Response.Write(Doc);
                    ////Response.End();


                    Attachment at = new Attachment(new MemoryStream(bytes), "Coupon.pdf");
                    MailMessage Msg = new MailMessage();
                    string FromMail = "xxxx@xxxxxxxxx.com";
                    string Password = "xxxxx";  // "XXXXXX" is sender password…
                    Msg.From = new MailAddress(FromMail);
                    // Recipient e-mail address..
                    string ToMail = Email;   //Receiver email id…
                    Msg.To.Add(ToMail);
                    string MsgBody = "Thank you for Registration your Laptop.<br><br>Coupon No : #" + Coupon + " <br><br> Please come out at our office with Coupon no.";
                    AlternateView htmlMsgView = AlternateView.CreateAlternateViewFromString(MsgBody, null, MediaTypeNames.Text.Html);
                    Msg.AlternateViews.Add(htmlMsgView);
                    Msg.Subject = "Subi Technologies :: Coupon";
                    Msg.Body = MsgBody;

                    //send the message
                    SmtpClient smtp = new SmtpClient("mail.xxxxxxxx.com");


                    //to authenticate we set the username and password properites on the SmtpClient
                    smtp.Credentials = new NetworkCredential(FromMail, Password);
                    Msg.Attachments.Add(at);
                    smtp.Send(Msg);
                }
            }
        }
    }

Connection string web.config asp.net

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
  <connectionStrings>
    <add name="conn" connectionString="Data Source=WIN-PC\SQLEXPRESS;Initial Catalog=st_SubiTechnologies;Integrated Security=True;" providerName="System.Data.SqlClient"/>
    <!--<add name="conn" connectionString="Data Source=.\SQLServer2012;Initial Catalog=st_SubiTechnologies;User Id=subi;Password=ysN9o2^6;Connect Timeout=120;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
</configuration>

save class

public static int Save(string Name, string Emailid, string PhoneNo, string LaptopBrand, string Model, string SerialNo, string Description, DateTime DOE, string Coupon)
    {
        int n;
        SqlCommand cmd = new SqlCommand();
        try
        {
            cmd.Connection = DataConnection.Con;
            cmd.CommandText = "Sp_Register_Save";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@rowId", 0);
            cmd.Parameters.AddWithValue("@Name", Name);
            cmd.Parameters.AddWithValue("@Emailid", Emailid);
            cmd.Parameters.AddWithValue("@PhoneNo", PhoneNo);
            cmd.Parameters.AddWithValue("@LaptopBrand", LaptopBrand);
            cmd.Parameters.AddWithValue("@Model", Model);
            cmd.Parameters.AddWithValue("@SerialNo", SerialNo);
            cmd.Parameters.AddWithValue("@Description", Description);
            cmd.Parameters.AddWithValue("@DOE", DOE);
            cmd.Parameters.AddWithValue("@Coupon", Coupon);
            cmd.Parameters.Add("@flag", SqlDbType.Int).Direction = ParameterDirection.Output;

            if (cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
            cmd.ExecuteNonQuery();
            n = Convert.ToInt32(cmd.Parameters["@flag"].Value);
            if (cmd.Connection.State == ConnectionState.Open)
            {
                cmd.Connection.Close();
            }
            return n;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

Fetch Store Procedure

USE [st_SubiTechnologies]
GO
/****** Object:  StoredProcedure [dbo].[Sp_Register_GetLastCoupon]    Script Date: 2/10/2017 10:56:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Sp_Register_GetLastCoupon]

--@flag int output
AS
BEGIN
begin transaction

select top(1) Coupon from tbl_registration order by rowId desc

--if @@ERROR=0
--begin
-- set @flag=1
-- commit transaction

--end
--else
--begin
-- set @flag=0
-- rollback transaction
--end
END

Save storeprocedure

USE [st_SubiTechnologies]
GO
/****** Object:  StoredProcedure [dbo].[Sp_Register_Save]    Script Date: 2/10/2017 10:46:56 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Sp_Register_Save]
@rowId int,
@Name varchar(300),
@Emailid varchar(300),
@PhoneNo varchar(20),
@LaptopBrand varchar(50),
@Model varchar(50),
@SerialNo varchar(200),
@Description varchar(700),
@DOE datetime,
@Coupon varchar(10),
@flag int output
AS
BEGIN
begin transaction

insert into [dbo].[tbl_registration](Name,Emailid,PhoneNo,LaptopBrand,Model,SerialNo,Description,DOE,Coupon)
values(@Name,@Emailid,@PhoneNo,@LaptopBrand,@Model,@SerialNo,@Description,@DOE,@Coupon)

if @@ERROR=0
begin
set @flag=1
commit transaction

end
else
begin
set @flag=0
rollback transaction
end
END

May 21, 2014

How to implement bangk payment gateway in html ?

HTML Code:

<!--bangk gateway-->
    <a href ='https://shopping.BANGK.com/?business_account_number=xxxxxxxxxxxxxxxxxxx&description=1&color=n%2Fa&size=%2Fa&weight=n%2Fa&price_per_item=99.00&currency_code_iso3=USD'
        Click to Buy Now
    </a>   // Replace xxxxxxxxxxxxxxxxxxx to your business_account_number of bangk gateway
<!--/bangk gateway-->





UI :