Saturday 23 May 2015

Insert Data into databas using Asp.Net MVC

Go through previous tutorial use business library as modal before preceding this tutorial. In Last tutorial we generated a student data modal


Step(1) : -In this Modal if i click on “Create New” link it goes to “http://localhost:12542/Student/Create” url , Means it expect Create method in Student controller but it didn’t get that so it gives exception , So get rid of this problem let’s write a “Create” method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer;

namespace MvcApplication2.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            BusinessLogic BL = new BusinessLogic();

            List<Student> student = BL.student.ToList();
            return View(student);
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

    }
}



Here if we see that this “Create” method is designed with “[HttpGet]” means this method responds only for the Get request or we can say that when user will come to this http://localhost:12542/Student/Create” url. It will not work for Post method.
Step(2) : - Let’s create a view for this “Create Method by right click on this method and add a view



Here modal class as “Student” and Scaffold template as Create ,this will automatically create a view. In generated view code make some changes for changing “Gender” textbox to as Dropdown box , So View code will like following code
At this time if you will run your application and click on “Create New” Link it will give error for @Scripts.Render("~/bundles/jqueryval")

So before run this application remove this line from your view code (it will at last) ,We will discuss on this in later tutorial.
So the view code will be
@model BusinessLayer.Student
@{
    ViewBag.Title = "Create";
}
<h2>
    Create</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Student</legend>
        <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="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>




Step(3): - when you will run your application and click on “create new”  then o/p will be



Step(4) : Here in above o/p or screen if we  click on Create button ,then it gives error that resource not found  because we didn’t create method for this. Means we have create [HttpPost] method.
Let’s  create a stored procedure for insertion data into database table
Create procedure insertStdDetail 
@StudentName nvarchar(50), 
@Gender nvarchar (10), 
@SchoolName nvarchar (50) 
as 
Begin 
 Insert into dbo.StudentInfo (StudentName, Gender, SchoolName ) 
 Values (@StudentName, @Gender, @SchoolName) 
End

Step(5):- Go to BusinessLayer library  project and in “BusinessLogic.cs” Class write a method for inserting value in database. For that take the following code
public void InsertStudentDetail(Student student)
        {
            string connectionString =
                    ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;

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

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

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

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

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


Step(6): -Write a post method in Student controller class of Create method , Take the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer;

namespace MvcApplication2.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            BusinessLogic BL = new BusinessLogic();

            List<Student> student = BL.student.ToList();
            return View(student);
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

   //Post Method for inserting data into database

        [HttpPost]
        public ActionResult Create(FormCollection formCollection)
        {
            Student student = new Student();           
            student.StudentName = formCollection["StudentName"];
            student.Gender = formCollection["Gender"];
            student.StudentClass = formCollection["StudentClass"];
           

            BusinessLogic BL =new BusinessLogic();

            BL.InsertStudentDetail(student);
            return RedirectToAction("Index");
        }

    }
}



We can create this method using parameters  

[HttpPost]
public ActionResult Create(string name, string gender, string studentClass)
{
    Student student = new Student();

   student.StudentName = name;
   student.Gender = gender;
   student.StudentClass = studentClass;
 

    BusinessLogic BL =new BusinessLogic();


            BL.InsertStudentDetail(student);

            return RedirectToAction("Index");

}


Basically we use “FormcCllection for getting Key and values.
Step(7):- Click on Create new link you will see screen and fill value and click on “Create” button.


After click on button it redirect to main page with updated student detail. 


Use Business Library as Modal in Asp.Net MVC

Here we will understand Modal with a Different library, means In MVC When we run a application then we need to specify correct controller name with Action method ,If we pass wrong name then it gives error.
But with modal this is different, means modal is optional and we can put it anywhere as library also.
Step (1):- Create a database table, So for that execute the below code
Create Table StudentInfo
(
     StudentID int identity primary key,
     StudentName nvarchar(50),
     Gender nvarchar(50),
     SchoolName nvarchar(50)
)
GO



Insert into StudentInfo values ('Munesh','Male','VIT')
Insert into StudentInfo values ('Rahul','Male','ABC')
Insert into StudentInfo values ('Reet','Female','XYZ')
Insert into StudentInfo values ('Anshuman','Male','PQR')


Also Create  a stored procedure for Retriving data from database
Create procedure GetAllStudents
as
Begin
 Select StudentID, StudentName, Gender, SchoolName 
 from StudentInfo
End

Step(2):-  Now Add  a new  library to the  solution .So for adding a Library to solution , Right click on Solution explorer  ->  Add ->New Project
Here New Project Screen will come ,from this screen we will select “Windows - >  “Class Library “ And give this library a meaningful name “BusinessLayer”.
This automatically generate a class as “Class1.cs” , So change the class name as “Student.cs” and Define the database property as we define in Modal Classes


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessLayer
{
    public class Student
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public string Gender { get; set; }
        public string StudentClass { get; set; }
    }
}



Step(3): -  Add a another class to this library for writing business logic code through that we will retrieve  the  data from database, Give this class name as “BusinessLogic.cs”.
Before writing code for retrieving the data from database first add some reference for Ado.Net code to this library
Go to reference folder of this library project - >Right click on Reference folder- >  .Net -> then select "System.Configuration" assembly. After that write following code to this class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace BusinessLayer
{
    public class BusinessLogic
    {
        public IEnumerable<Student> student
        {
            get
            {
                string connectionString =                    ConfigurationManager.ConnectionStrings["Conncet"].ConnectionString;

                List<Student> employees = new List<Student>();

                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand("GetAllStudents", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Student student = new Student();
                        student.StudentID = Convert.ToInt32(rdr["StudentID"]);
                        student.StudentName = rdr["StudentName"].ToString();
                        student.Gender = rdr["Gender"].ToString();
                        student.StudentClass = rdr["SchoolName"].ToString();
                     

                        employees.Add(student);
                    }
                }

                return employees;
            }
        }
    }
}

After everything done build this Library project.
Connection string in Web config will be
<connectionStrings>
    <add name="Connect"
        connectionString="server=.; database=MVCApplication; integrated security=SSPI"
        providerName="System.Data.SqlClient"/>
  </connectionStrings>


Step(4): -  Now Go to your MVC Project add the reference of this library project, using right click on Reference folder.


Step(5): -  Now go to controller folder and add a controller to this project ,give the name for this controller as “Student”. In this controller add the name space for BusinessLogic project.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer;

namespace MvcApplication2.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            BusinessLogic BL = new BusinessLogic();

            List<Student> student = BL.student.ToList();
            return View(student);
        }

    }
}



Step(6):- Now Right click on this Controller method and add a view , While creating view select Modal class as “Student” and Give Scaffold template as “List”, So it will create a list for us.


@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) {
    <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 }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
        </td>
    </tr>
}

</table>
</div>


Before running this application changes the controller name in Route.config file.
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
            );
        }


Now Run This Application you will get o/p like this




Here if you will click on any link it will give exception because we didn’t work on these links.

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