Friday, 23 February 2018

Save Data MVC Ajax

Target audience

Beginners learning MVC and want to save a from record into database using ajax.

Table Structure

Roll
Bigint
Name
Varchar(20)
City
Varchar(20)

Store Procedure

USE[Girfa_DB]
GO

SETANSI_NULLSON
GO
SETQUOTED_IDENTIFIERON
GO

ALTERProc[dbo].[AddRecord]
(
@rollbigint,
@namevarchar(20),
@cityvarchar(20)
)
AS

BEGIN
       SETNOCOUNTON;
              INSERTintoStudent(roll,Name,City)values(@roll,@name,@city)
       SETNOCOUNTOFF;
END

Model


publicclassStudentModel
{
publicint Roll { get; set; }
publicstring Name { get; set; }

publicstring City { get; set; }
}

Java Script


functionSaveData() {

var Userobj =
        {
            Roll: $j("#txtRoll").text(),

            Name: $j("#txtName").val(),
            City: $j("#txtCity").val(),
        }

    $.ajax({
url: '/Master/SaveData/',
dataType: "json",
type: "POST",
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(Userobj),
success: function (data) {

if (data.sMessage == "1")
alert("Data Saved");
else
alert('Some error occured');
        }
    });

}

Controller


public JsonResult SaveData(StudentModel Prob)
{
    string ErrMsg = "";

    StuRepository obj = new StuRepository();

    if (obj.SaveData(Prob) == true)
    {
        return Json(new { sMessage = "1", JsonRequestBehavior.AllowGet });
    }
    else
    {
        return Json(new { sMessage = "0", JsonRequestBehavior.AllowGet });
    }

}

Repository


public bool SaveData(StudentModel ob)
{
String result = "";
try
    {
using (SqlConnectiondbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
        {
using (SqlCommand cmd = newSqlCommand("[dbo].[AddRecord]", dbcon))
            {
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@roll", ob.Roll);
cmd.Parameters.AddWithValue("@name", ob.Name);
cmd.Parameters.AddWithValue("@city", ob.City);


if (dbcon.State == ConnectionState.Closed)
dbcon.Open();
cmd.ExecuteNonQuery();
result = "1";
            }
        }
    }
catch (Exception ex)
    {
ErrMsg = ex.Message;
    }
if (result == "1")
return true;
else
return false;
}

CSHTML



@{
ViewBag.Title = "tmp";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Save Data</h2>
<form>
    Roll : <inputtype="text"id="txtRoll"/><br/>
    Name : <inputtype="text"id="txtName"/><br/>
    City : <inputtype="text"id="txtCity"/><br/>
<inputtype="button"value="Save"onclick="SaveData()"/>
</form>