.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Visual Studio >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Students Data update to the DataBase

Posted By:Daniel Bhagathsingh       Posted Date: December 17, 2013    Points: 40    Category: Visual Studio    URL: http://www.dotnetspark.com  

If you want update any data into the database,you can use this coding.this is making by using MVC(Business layer) concepts.
 

StudentController.cs
******************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer;

namespace MVCDemo14.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            StudentBusinessLayer studentBusinessLayer = new StudentBusinessLayer();
            List<Student> students = studentBusinessLayer.Students.ToList();
            return View(students);
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View();

        }
        [HttpPost]
        public ActionResult Create(FormCollection formCollection)
        {
            Student student = new Student();
            student.SId = Convert.ToInt32(formCollection["SId"]);
            student.Name = formCollection["Name"];
            student.Age = Convert.ToInt32(formCollection["Age"]);
            student.Gender = formCollection["Gender"];
            student.Course = formCollection["Course"];
            student.Departement = formCollection["Departement"];
            student.Place = formCollection["Place"];

            StudentBusinessLayer studentBusinessLayer = new StudentBusinessLayer();
            studentBusinessLayer.AddEmployee(student);

            return RedirectToAction("Index");
         
        }

     
    }
}
*****************
StudentBusinessLayer.cs
***************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;


namespace BusinessLayer
{
    public class StudentBusinessLayer
    {
        public IEnumerable<Student> Students
        {
            get {
                string connectionString =
                    ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

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

                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand("spGetAllStudents", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Student student = new Student();
                        student.SId = Convert.ToInt32(rdr["SId"]);
                        student.Name = rdr["Name"].ToString();
                        student.Age = Convert.ToInt32(rdr["Age"]);
                        student.Gender = rdr["Gender"].ToString();
                        student.Course = rdr["Course"].ToString();
                        student.Departement = rdr["Departement"].ToString();
                        student.Place = rdr["Place"].ToString();
                       

                        students.Add(student);
                    }
                }

                return students;
            }
           
        }
         
                  public void AddEmployee(Student student)

            {
                string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand("spAddStudent", con);
                    cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramSId = new SqlParameter();
paramSId.ParameterName="@SId";
paramSId.Value=student.SId;
cmd.Parameters.Add(paramSId);
SqlParameter paramName = new SqlParameter();
paramName.ParameterName="@Name";
paramName.Value=student.Name;
                    cmd.Parameters.Add(paramName);
SqlParameter paramAge = new SqlParameter();
paramAge.ParameterName="@Age";
paramAge.Value=student.Age;
cmd.Parameters.Add(paramAge);
SqlParameter paramGender = new SqlParameter();
paramGender.ParameterName="@Gender";
paramGender.Value=student.Gender;
cmd.Parameters.Add(paramGender);
SqlParameter paramCourse = new SqlParameter();
paramCourse.ParameterName="@Course";
paramCourse.Value=student.Course;
cmd.Parameters.Add(paramCourse);
SqlParameter paramDepartement = new SqlParameter();
paramDepartement.ParameterName="@Departement";
paramDepartement.Value=student.Departement;
cmd.Parameters.Add(paramDepartement);
SqlParameter paramPlace = new SqlParameter();
paramPlace.ParameterName="@Place";
paramPlace.Value=student.Place;
cmd.Parameters.Add(paramPlace);
                    
con.Open();
                    cmd.ExecuteNonQuery();
                  }

                  }
public  SqlParameter paramname { get; set; }}
}

******************
Student.cs
**********************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLayer
{
    public class Student
    {
        public int SId { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
        public string Course { get; set; }
        public string Departement { get; set; }
        public string Place { get; set; }
    }
}
***********************
Create.cshtml
*************************

@model BusinessLayer.Student

@{
    ViewBag.Title = "Create";
}
<div style="font-family: Arial">

    <h2>Create</h2>

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>Student</legend>

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

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

            <div class="editor-label">
                @Html.LabelFor(model => model.Age)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Age)
                @Html.ValidationMessageFor(model => model.Age)
            </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="Femaale",Value="Female"}
       
       },"Select Gender")
                @Html.ValidationMessageFor(model => model.Gender)
            </div>

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

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

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

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

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

</div>
*******************************************
Index.cshtml
***************************

@model IEnumerable<BusinessLayer.Student>

@{
    ViewBag.Title = "Index";
 }



<center>
<div style="font-family:Arial;background-color:#B8E62E">
<h2><font color="#9900CC">Welcome By DANIEL SINGH X...</font></h2>


<table border="1" bgcolor="#00FFFF">
    <tr bgcolor="#D6AD99">
        <th>
            @Html.DisplayNameFor(model => model.SId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Course)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Departement)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Place)
        </th>
        <th>Action</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.SId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Course)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Departement)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Place)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>
    <p>
    @Html.ActionLink("Add New", "Create")
</p>
</div>
    </center>
    
 **************************
Web.config

***************************
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
<connectionStrings>
    <add name="DBCS"
         connectionString="server=ADMIN-PC\DANIEL; database=Jesus; integrated security=SSPI"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend