Thursday, 29 March 2018

Get Single value from database using ajax



Store Procedure


USE [Girfa_StudentHelp]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER proc [dbo].[GetPhone]
(
   @id int

)
as
begin

select Phone  from dbo.Student
where roll=@id

end

CSHTML


  Roll : <input type="text" id="txtRoll">
  Phone : <input type="text" id="txtPhone"><br />
  <input type="button" value="Saerch Phone" onclick="getPhone()" />

Java Script


function getPhone()
{
       $j.ajax({
       url: '/Student/getPhoneDB/',
       dataType: "json",
       type: "GET",
      contentType: 'application/json; charset=utf-8',
      data: { roll: $("#txtRoll").val() },
                    success: function (data) {
                        $("$txtPhone").val(data.Phone);
                    }
                });
                  
}

Controller



public JsonResult getPhoneDB(string roll)
{
    StudentRepository ob = new StudentRepository();
    return Json(new { sMessage = ob.getPhoneDB(roll) }, JsonRequestBehavior.AllowGet);

}
 

Repository


public string getPhoneDB(string roll)
{
    string Phone = "";
    try
    {
        using (SqlConnection dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
        {
            using (SqlCommand cmd = new SqlCommand("[dbo].[GetPhone]", dbcon))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@id", Convert.ToInt32(roll));


                if (dbcon.State == ConnectionState.Closed)
                    dbcon.Open();
                Phone = Convert.ToString(cmd.ExecuteScalar());
            }
        }
    }
    catch (Exception ex)
    {

    }
    return Phone;
}