Thursday 11 June 2015

Delete record from database using Asp.net MVC

In previous article we learn how to create a businessobject modal and how to update data in database .In this article we will learn how to Delete data modal on delete click event . Before proceeding this tutorial go to this link


Delete Database Record using Get Request
1.   Go to your sql Server and Create a stored procedure for deleting database record according to ID,
Stored procedure will be like following
Create procedure DeleteStudentInfo
@Id int
as
Begin
 Delete from StudentInfo
 where StudentID = @Id
End

2.    Now go to the BussinessLayer Library project and in BusinessLogic.cs class add a Delete function, For Deleting the data from database.
Function code will be
public void DeleteStudentInfo(int id)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("DeleteStudentInfo", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter ExecuteID = new SqlParameter();
                ExecuteID.ParameterName = "@Id";
                ExecuteID.Value = id;
                cmd.Parameters.Add(ExecuteID);

                con.Open();
                cmd.ExecuteNonQuery();
            }
        }
                cmd.ExecuteNonQuery();
            }
        }


3.   Add a controller to this project for deleting the row based on Row id. Delete Action method will be
public ActionResult Delete(int id)
        {
            BusinessLogic BL = new BusinessLogic();

            BL.DeleteStudentInfo(id);
            return RedirectToAction("Index");
        }


4.   Now run your application and click on first Row  delete link , when you will click on this link it will delete this record from  database.


Deleting record using GET request is bad because while deleting using GET request it take a link like “http://localhost/MVCFirstApplication/StudentInfo/Delete/1”.. Here if I give link in image then it delete the data from database , so it is bad.
Delete we should do with Post request.

Delete Using POST Request:-
Step(1):-  Create a Action Method for the Delete record using POST Request(HttpPost)  . Action  Method will be
[HttpPost]
        public ActionResult Delete(int id)
        {
            BusinessLogic BL = new BusinessLogic();

            BL.DeleteStudentInfo(id);
            return RedirectToAction("Index");
        }


Step(2):-  Now we want that Delete link should be in button (it is in Link)  format So for that we need to change in Index View ,that we design in tutorial “Business Library as Modal”.
That update Index View will be
@model IEnumerable<BusinessLayer.Student>

@{
    ViewBag.Title = "Index";
}

<div>
<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table border = "1">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.StudentName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.StudentClass)
        </th>
        <th>
        Action To be Taken
        </th>
    </tr>

@foreach (var item in Model) {
   
    using(@Html.BeginForm("Delete","Student",new { id=item.StudentID }))
    {
        <tr>
        <td>
            @Html.DisplayFor(modelItem => item.StudentName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.StudentClass)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.StudentID }) |
            @Html.ActionLink("Details", "Details", new { id = item.StudentID }) |
            <input type="submit" value="Delete" />
        </td>
       
    </tr>
    }
}

</table>
</div>


Step(3):- Now if you will run your application then your Index View will be look like this


Step(4):-  If we want to client side confirmation for delete button we need to add Java Script function at OnClick event of submit button in index View code will be
  <input type="submit" value="Delete" onclick="return confirm('Are you  want to delete record Of Name = @item.StudentName');" />


Now run your application and Click on Delete button you will see confirmation message ,If you click on Cancel it will not delete data but when you will click on OK it will delete data from database.



Tuesday 26 May 2015

Editing Modal and Update modal in Asp.Net MVC

In previous article we learn how to create a business object modal and how to insert data in database .In this article we will learn how to Edit data modal on edit click event . Before proceeding this tutorial go to this


Editing  Data modal
We want that when we click on EDIT link it should render to the Index Action method of StudentController , with specific ID .
So for that first create a Action method for this and create a view for editing these data.
Action method will be like
[HttpGet]
        public ActionResult Edit(int ID)
        {
            Student student = new Student();
           
            BusinessLogic BL = new BusinessLogic();
            Student _student = BL.student.Where(c => c.StudentID == ID).SingleOrDefault();
            return View(student);
        }


After that we need for a View  , so create a Edit View by right click on this action method and add a view


Delete the following script from the view
@section Scripts 
{
    @Scripts.Render(
"~/bundles/jqueryval")
}

After that View Code will be like following
@model BusinessLayer.Student

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<div style = "font-family:Arial>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Student</legend>

        @Html.HiddenFor(model => model.StudentID)

        <div class="editor-label">
            @Html.LabelFor(model => model.StudentName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.StudentName)
            @Html.ValidationMessageFor(model => model.StudentName)
        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
           
            @Html.DropDownList("Gender", new List<SelectListItem>
            {
            new SelectListItem { Text = "Male", Value="Male" },
            new SelectListItem { Text = "Female", Value="Female" }
            }, "Select Gender")

           
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.StudentClass)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.StudentClass)
            @Html.ValidationMessageFor(model => model.StudentClass)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
</div>




Run you application you will see All the data from database in grid like this

When we will click on Edit link it will redirect to EDIT View and look like that

Here you edit the data and click on Save button you will see updated value
Updating  Datamodal
Step(1) : -Now if we click on Save button it gives error because The edit method is using “[HttpGet]” attribute means that this action result Edit method is only accept get request.
For updating the Edit value in database, first create the stored procedure for update ion, So Stored procedure will be like following

Create procedure UpdateStudentInfo     
@StudentID int,
@StudentName nvarchar(50),     
@Gender nvarchar (10),     
@SchoolName nvarchar (50)
as     
Begin     
 Update StudentInfo Set
 StudentName = @StudentName,
 Gender = @Gender,
 SchoolName = @SchoolName
 Where StudentID = @StudentID
End

Step(2): Now go to the BussinessLayer Library project and in BusinessLogic.cs class add a save function, For saving the data into databse.
public void SaveStudentInfo(Student student)
        {
            string connectionString =
                    ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("UpdateStudentInfo", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter studentId = new SqlParameter();
                studentId.ParameterName = "@StudentID";
                studentId.Value = student.StudentID;
                cmd.Parameters.Add(studentId);

                SqlParameter studentName = new SqlParameter();
                studentName.ParameterName = "@StudentName";
                studentName.Value = student.StudentName;
                cmd.Parameters.Add(studentName);

                SqlParameter Gender = new SqlParameter();
                Gender.ParameterName = "@Gender";
                Gender.Value = student.Gender;
                cmd.Parameters.Add(Gender);

                SqlParameter schoolname = new SqlParameter();
                schoolname.ParameterName = "@SchoolName";
                schoolname.Value = student.StudentClass;
                cmd.Parameters.Add(schoolname);              

                con.Open();
                cmd.ExecuteNonQuery();
            }

        }


Step(3): - Go to Student Controller and add a Edit post method for updating the value. Method code will like following
[HttpPost]
        public ActionResult Edit()
        {
            if (ModelState.IsValid)
            {
                Student student = new Student();
                UpdateModel<Student>(student);
                BusinessLogic BL = new BusinessLogic();

                BL.SaveStudentInfo(student);
                return RedirectToAction("Index");
            }
            return View();
        }


Step(4): Now run your application and click on edit button change the value and save it .. you will see updated value.


After saving edited value will look like this


C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...