Monday 26 February 2018

Delete Record MVC Ajax



Target User

Beginner He/She learning MVC and want to delete a record by clicking on delete button on table row.

Table Stucture


Field
Data Type
Roll
Bigint
Name
Varchar(20)
City
Varchar(20

Model

public class StudentModel
{
    public int Roll { get; set; }
    public string Name { get; set; }

    public string City { get; set; }
}

Controller

//Show Record Page
public ActionResult ShowData()

{
    StudentRepository ob = new StudentRepository();
    return View(ob.getdatas());
}

//Delete Student Record 
public JsonResult DeleteStu(CustomerModel obj)
{
    StudentRepository ob = new StudentRepository();

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


Repository

//Show all Student Record
public List<CustomerModel> getdatas()
{
    List<CustomerModel> Record = new List<CustomerModel>();
    try
    {
        using (SqlConnection dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
        {
            using (SqlCommand cmd = new SqlCommand("[dbo].[ShowData]", dbcon))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                      

                if (dbcon.State == ConnectionState.Closed)
                    dbcon.Open();
                using (SqlDataReader drGetRequestedPin = cmd.ExecuteReader())
                {
                    if (drGetRequestedPin.HasRows)
                    {

                        while (drGetRequestedPin.Read())
                        {
                            CustomerModel data = new CustomerModel();
                            data.ID = drGetRequestedPin.IsDBNull(0) ? "0" : Convert.ToString(drGetRequestedPin[0]);
                            data.FullName = drGetRequestedPin.IsDBNull(1) ? "-" : Convert.ToString(drGetRequestedPin[1]);
                            data.installationdate = drGetRequestedPin.IsDBNull(2) ? "0" : Convert.ToString(drGetRequestedPin[2]);
                            Record.Add(data);
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {

    }
    return Record;
}


//Delete Student Record
public bool DeleteData(string id)
{
    string result = "";
    try
    {
        using (SqlConnection dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
        {
            using (SqlCommand cmd = new SqlCommand("[dbo].[DeleteData]", dbcon))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@id", id);
                     
                if (dbcon.State == ConnectionState.Closed)
                    dbcon.Open();
                cmd.ExecuteNonQuery();
                result = "1";
            }
        }
    }
    catch (Exception ex)
    {
               
    }
    if (result == "1")
        return true;
    else
        return false;
}

CSHTML



@model IEnumerable<Girfa.Models.StudentModel>
@{
    ViewBag.Title = "tmp";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>tmp</h2>


<table border="1" class="table">
    <thead>
        <tr><th>Roll</th><th>Roll</th><th>Name</th><th>Action</th></tr>
    </thead>
    <tbody>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelitem => item.ID)
                </td>
                <td class="center">
                    @Html.DisplayFor(modelitem => item.FullName)
                </td>
                <td class="center">
                    @Html.DisplayFor(modelItem => item.installationdate)
                </td>
                <td class="center">
                  <input type="button" value="Delete" onclick="DeleteData(@item.ID)" />
                </td>
            </tr>
        }

    </tbody>

</table>


Java Script


<script>
function DeleteData(sid)
{
    var Userobj =
        {
            ID:sid,
        }
    $.ajax({
        url: '/Usertask/DeleteStu/',
        dataType: "json",
        type: "POST",          
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(Userobj),
        success:
            function (data) {
                if (data.sMessage == 1)
                alert("Record Updated");
            else
                alert('Some error occured');            
        }
    });
}
</script>


Store Procedure

/* Show All Student  Record */

USE [Girfa_ StuDB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[ShowData]

AS
BEGIN
       SET NOCOUNT ON;
              select * from tmp
       SET NOCOUNT OFF;
END


 /* Procedure delete student record */

 USE [Girfa_StuDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[DeleteData]
(
       @id bigint
)
AS
BEGIN
       SET NOCOUNT ON;
              delete from dbo.tmp where id=@id
       SET NOCOUNT OFF;
END


No comments:

Post a Comment