May 18, 2011

Code Example ADO.NET Entity Framework "Insert Update Delete" data in MVC application

How we can use ASP.NET MVC Framework check this post

In the above Post example I have used ADO.NET to insert the data in SQLServer Db (Student Table)
Now In this post I 'll Insert and Update Data in Student_Marks table(Student_id,Marks)in One More view
Using ADO.NET Entity framework.

1.) Creating the ADO.NET Entity Data Model 
     Check the below post to create ADO.NET Entity Data Model.

2.) We will Add Our Form AddStudentMarks within the same App
3.)Right click on Models Add new class StudentmarksModel.cs
4.)Code On StudentMarksModel.cs Create property corresponding to each Form Field + Write the Validation 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace TestMVCapplication.Models
    public class StudentMarksModel

        [Required(ErrorMessage = "* Required")]
        public string  Marks { get; set; }

        public string Student_Id { get; set; }

        public IEnumerable<SelectListItem> StudentList { get; set; }


5.)We’ll then add a “StudentMarksController.cs” controller class to our project's Controllers folder that exposes two “AddStudentMarks” action methods.  

The first action method is called when an HTTP-GET request comes for the /StudentMarks/Create URL.  It will display a blank form for entering Student data. 
 The second action method is called when an HTTP-POST request comes for the /Studentmarks/Create URL.  It maps the posted form input to a StudentMarks object, verifies that no binding errors occurred, and if it is valid will eventually save it to a database(Business Logic)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Objects;
using TestMVCapplication.Models;

namespace TestMVCapplication.Controllers
    public class StudentMarksController : Controller
        // GET: /StudentMarks/
        public ActionResult AddStudentMarks()
          TestMVCEntities3 DBobj = new TestMVCEntities3();

          //ViewData["StudentList"] = new SelectList(DBobj.Student, "Student_Id", "Name");

          //return View();

         //To set the Student Names in DropdownList
          var model = new StudentMarksModel();
          model.StudentList = new SelectList(DBobj.Student, "Student_Id", "Name");
           return View(model);


        public ActionResult AddStudentMarks(StudentMarksModel model)
           //Add Data Using Entity Framework in ADO.NET

            TestMVCEntities3 DBobj = new TestMVCEntities3();

            int StudentId = Convert.ToInt32(model.Student_Id);

            //Check If the reord exists with the Dropdownlist selcted value as Student_Id
            var record = DBobj.Student_Marks.FirstOrDefault(m => m.Student_Id == StudentId);
            //If record exists update it with the value entered in marks textbox
            if (record != null)
                Student_Marks e = (from e1 in DBobj.Student_Marks

                                   where e1.Student_Id == StudentId

                                   select e1).First();
                e.Marks = int.Parse(model.Marks);


            //If record doesn't exists Insert the new record
                Student_Marks sMarks = new Student_Marks();

                sMarks.Student_Id = int.Parse(model.Student_Id);
                sMarks.Marks = int.Parse(model.Marks);


            //To set the Student Names in DropdownList
            var modelsend = new StudentMarksModel();
            modelsend.StudentList = new SelectList(DBobj.Student, "Student_Id", "Name");

            return View(modelsend);


7.)After we’ve implemented our controller, we can right-click within one of its action methods and choose the “Add View” command within Visual Studio – which will bring up the “Add View” dialog
Add  AddStudentMarks.aspx view file for us under the \Views\StudentMarks\ 
8.)Design the form on AddStudentMarks.aspx using HTMlHelper Class

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestMVCapplication.Models.StudentMarksModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">


<form id="form1" runat="server">
<% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
           <div class="editor-field">
                <%= Html.DropDownListFor(x => x.Student_Id,Model.StudentList)%>
                <%= Html.ValidationMessageFor(m => m.Student_Id) %>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Marks) %>
                <%= Html.ValidationMessageFor(m => m.Marks) %>
                <input type="submit" value="Submit" />
        <p id="result"><%=TempData["Message"] %></p>
    <% } %>

9)Add The link for Student in Site.Master

10) Run the app
11.)Click StudentMarks

      StudentList will be filled up from Student table in DropDownlist

12)select the name and insert Marks if The student_id already Exists in Student_Marks It will 
   update the record if it does not exist it will add new record with the selected Student_Id from drop Down and input marks

13.) See the Updated Record in DB

No comments:

Post a Comment