Pages

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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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").val(),

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

    $.ajax({
url: '/Master/SaveData/',
dataType: "json",
type: "POST",

contentType: 'application/json; charset=utf-8',
data: JSON.stringify(Userobj),
success: function (data) {

if (data.sMessage == "1")
alert("Data Saved");
else
alert(data.sMessage);
        }
    });

}

Controller


public JsonResult SaveInvoiceAmount(InvoiceModal data)
{
            string ErrMsg = "";

            UserRepository obj = new UserRepository();

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


  }

Repository


public bool SaveData(StudentModel ob,ref string ErrMsg)
{
String result = "";
try
    {
using (SqlConnection dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
        {
using (SqlCommand cmd = new SqlCommand("[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>


No comments:

Post a Comment