Friday 12 June 2015

CRUD Operation in Asp.Net MVC using Entity Framework

Here we will learn CURD Operation in Asp.net MVC Using Entity Framework.
For More Detail About Entity Framework Go to EntityFramework Tutorials.
1.   First Go to Sql Server and Execute following query for Student Department and Student Information.
Create table stdDepartment
(
 Id int primary key identity,
 Name nvarchar(50)
)

Insert into stdDepartment values('Teacher')
Insert into stdDepartment values('HOD')
Insert into stdDepartment values('Professor')

Create Table Student
(
     StudentID int identity primary key,
     StudentName nvarchar(50),
     Gender nvarchar(50),
     SchoolName nvarchar(50)
)

Alter table Student add DepartmentId int

Alter table Student
add foreign key (DepartmentId)
references stdDepartment(Id)

Insert into Student values ('Munesh','Male','VIT',1)
Insert into Student values ('Rahul','Male','ABC',2)
Insert into Student values ('Reet','Female','XYZ',2)
Insert into Student values ('Anshuman','Male','PQR',3)
Insert into Student values ('Simi','Female','NIT',3)
Insert into Student values ('Nency','Female','MIT',2)
Insert into Student values ('XYZ','Male','PQR',1)


Go to Visual stdio -> NewProjct -> Select MVC4 Web Application (give application name) -> select Empty website with Rezor.

2.   Now Install Entity Framework to your application For this Go here.
3.   After Installing Entity Framework Add “Ado.Net Entity DataModal” by right click on “Modals”, And Give the name for this as “StudentDataModal”.




4.   When You will click Add button here you will see another window for  “EntityData modal Wizard” from there you select “Generate From DataBase”, And Click Next
5.   In This window you give you database connection and select your database ,


After click, on Continue Button Below screen will show there you will database connection and Test your connection and click OK



Then Click Next
6.   In this screen select your Database Tables and give Modal Name then click FINISH Button


7.   When you will click on finish button it will create StudentDepartment and Student Entity, change their  name also


8.   Right Click on Controller and add a controller and give details in controller like below

After that click on Add
9.   When you will click on add it will create View automatically , You can see in View folder


10.                At this time if we run our application it will error that “Resource cannot found” this is because in RouteConfig file the default controller name is “Home “ controller , so change this controller name as “Student” controller and run application.



Delete the following Script from “Create.csHtml and “Detail.csHtml” View

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")


Now run your application and see the output and perform all the operations.




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.



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...