ASP.Net MVC with Entity Framework Cognizant Handsons

ASP.Net MVC with Entity Framework Cognizant Handson Programs

In this article, we are going to cover all ASP.Net MVC with Entity Framework Cognizant Handson Programs.

Ex 1.1 – Controllers and Actions

Ex1Controller.cs

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

namespace ASP_App1.Controllers
{
    public class Ex1Controller : Controller
    {
        List<String> breakingNews = new List<String>()
        {
            "PM visit brings business",
            "10% slash in GST",
            "Top Player announced retirement",
            "India wins series"
        };

        public ActionResult NewsByChoice(int id) => base.Content(breakingNews[id - 1]);

        public ActionResult AllNews() => base.Content(string.Join("\n", breakingNews));
    }
}

Ex 1.2 Controllers and Actions

Ex2Controller.cs

using System.Reflection.Emit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace ASP_App1.Controllers
{

    enum CourseType
    {
        JavaCourse = 1, DotNetCourse
    }

    public class Ex2Controller : Controller
    {
        public ActionResult Course(int id) => base.RedirectToAction(((CourseType)id).ToString());

        public ActionResult JavaCourse() => base.View();

        public ActionResult DotNetCourse() => base.View();
    }
}

Also Read : CourseRepository Entity Framework Cognizant Handson Solution

DotNetCourse.cshtml

<h1>DotNetCourse</h1>

JavaCourse.cshtml

<h1>DotNetCourse</h1>

Ex 2.1 – Working With View Bag

HomeController.cs

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

namespace ASP_App1.Controllers
{

    public class HomeController : Controller
    {

        string business = "Flipkart";
        string type = "E-commerce";
        int founded = 2007;
        string website = "www.flipkart.com";


        [Route("flipkart/info")]
        public ActionResult About()
        {
            ViewBag.Business = business;
            ViewBag.Type = type;
            ViewBag.Founded = founded;
            ViewBag.Website = website;

            return View();
        }
        // Implement 'About' action with Route 'flipkart/info'
    }
}

About.cshtml

<h1>@ViewBag.Business</h1>
<h3>@ViewBag.Type</h3>
<h4>@ViewBag.Founded</h4>
<h4>@ViewBag.Website</h4>

Ex 3.1 Working With Model Binding

Ex3Controller.cs

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

namespace ASP_App1.Controllers
{
    public class Ex3Controller : Controller
    {
        private Course CreateJavaCourse() => new Course { CourseId = "C101", CourseName = "Java", Duration = 40, Level = "Beginner" };

        private Department CreateFakeDept() => new Department() { CourseList = new List<string>() { "Java", "DotNet", "Python", "Ruby" } };

        public ActionResult Index()
        {
            return base.RedirectToAction(nameof(CourseDescription), this.CreateJavaCourse());
        }

        public ActionResult IndexChoice(int id)
        {
            if (id == 1)
            {
                return base.RedirectToAction(nameof(CourseDescription), this.CreateJavaCourse());
            }
            else if (id == 2)
            {
                return base.RedirectToAction(nameof(CourseList), this.CreateFakeDept());
            }
            return null;
        }

        public ActionResult CourseDescription(Course course)
        {
            return View(course);
        }

        public ActionResult CourseList(Department department)
        {
            return View(department);
        }
    }
}

Course.cs

// THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASP_App1.Models
{
    public class Course
    {
        public String CourseName { get; set; }
        public String CourseId { get; set; }
        public int Duration { get; set; }
        public string Level { get; set; }

    }

    public class Department
    {
        public List<String> CourseList { get; set; }
    }
}

CourseDescription.cshtml

@model ASP_App1.Models.Course

<h2>Course Details</h2>

<table>
  <tr>
    <th>Course ID:</th>
    <th><input type="text" id="CourseId" name="CourseId" readonly="readonly" value="@Model.CourseId" /></th>
  </tr>
  <tr>
    <th>Course Name:</th>
    <th><input type="text" id="CourseName" name="CourseName" readonly="readonly" value="@Model.CourseName" /></th>
  </tr>
  <tr>
    <th>Course Duration:</th>
    <th><input type="text" id="Duration" name="Duration" readonly="readonly" value="@Model.Duration" /></th>
  </tr>
  <tr>
    <th>Course Level:</th>
    <th><input type="text" id="Level" name="Level" readonly="readonly" value="@Model.Level" /></th>
  </tr>
</table>

CouseList.cshtml

@model ASP_App1.Models.Department

<h2>Available Courses</h2>

@foreach (var coursename in @Model.CourseList)
{
  @coursename
  <br />
}

Ex 3.2 Working With Model Binding

Ex3Controller.cs

using ASP_App1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP_App1.Controllers
{
    public class Ex3Controller : Controller
    {
        List<ShoppingCart> carts = new List<ShoppingCart>()
        {
            new ShoppingCart("CA1","Shoe", 3000,"Sport"),
            new ShoppingCart("CA2", "Shirt", 1500, "Men's Wear"),
            new ShoppingCart("CA3","Watch", 4000,"Accessories"),
            new ShoppingCart("CA4","Samsung",15000,"Mobiles")
        };

        public ActionResult Cart(int id) => View(nameof(Cart), carts[id - 1]);

        [HttpPost]
        public ActionResult Cart([Bind] ShoppingCart cart) => View(nameof(Cart), cart);
    }
}

ShoppingCart.cs

//THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASP_App1.Models
{
    public class ShoppingCart
    {
        public String CartId { get; set; }
        public String ItemName { get; set; }
        public int Price { get; set; }
        public string ItemType { get; set; }

        public ShoppingCart(String cartId, String itemName, int price, String itemType)
        {
            this.ItemName = itemName;
            this.CartId = cartId;
            this.Price = price;
            this.ItemType = itemType;
        }
    }
}

Cart.cshtml

@model ASP_App1.Models.ShoppingCart

<h1>Shopping Cart Details</h1>

<p>@Model.CartId</p>
<p>@Model.ItemName</p>
<p>@Model.ItemType</p>
<p>@Model.Price</p>

Ex 5-1 Partial View

ChTrust.cshtml

@using (Html.BeginForm())
{
  <table>
  <tr>
    <th>@Html.Partial("_HeaderNavBar")</th>
  </tr>
  <tr>
    <th>
      <section style="margin:50px;">
        <table>
          <tr>
            <td>@Html.Label("Name")</td>
            <td>@Html.TextBox("txName")</td>
          </tr>
          <tr>
            <td>@Html.Label("Phone Number")</td>
            <td>@Html.TextBox("txPhoneNumber")</td>
          </tr>
          <tr>
            <td>@Html.Label("Donation For")</td>
            <td>@Html.DropDownList("ddlDonation", new List<SelectListItem>()
              {
              new SelectListItem() {Text="Education",Value="Education" },
              new SelectListItem() {Text="Hospital",Value="Hospital" },
              new SelectListItem() {Text="Old People Caring Home",Value="Old People Caring Home" }
              })</td>
          </tr>
          <tr>
            <td>@Html.Label("Amount")</td>
            <td>@Html.TextBox("txAmount")</td>
          </tr>
          <tr>
            <td>@Html.Label("Donation Type")</td>
            <td>
              @Html.RadioButton("rbDonationType", "One Time Donation", isChecked: true)One Time Donation
              @Html.RadioButton("rbDonationType", "Recurring Donation")@Html.Label("Recurring Donation")
            </td>
          </tr>
          <tr>
            <td></td>
            <td><button type="submit" id="submit">PROCEED</button></td>
          </tr>
        </table>
      </section>
    </th>
  </tr>
  <tr>
    <th>@Html.Partial("_FooterNavBar")</th>
  </tr>
</table>
}

ChTrustController.cs

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

namespace ASP_App1.Controllers
{
    public class ChTrustController : Controller
    {
        public ActionResult ChTrust() => View();

        public PartialViewResult _HeaderNavBar() => PartialView(nameof(_HeaderNavBar));

        public PartialViewResult _FooterNavBar() => PartialView(nameof(_FooterNavBar));
    }
}

_HeaderNavBar.cshtml

<header>Help Our Charity</header>

_FooterNavBar.cshtml

<Footer>Thank you For Your Support</Footer>

Ex 4-1 Working With HTTP POST

Course.cs

//THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASP_App1.Models
{
    public class Course
    {
        public String CourseName { get; set; }
        public String CourseId { get; set; }
        public int Duration { get; set; }
        public string Level { get; set; }
    }
}

Course.cshtml

@model ASP_App1.Models.Course

<h1>Enter New Course Details</h1>

<form action="post">
  <label>Course Name</label>
  <input type="text" asp-for=@Model.CourseName>
  <br>

  <label>Course Id</label>
  <input type="text" asp-for=@Model.CourseId>
  <br>

  <label>Duration</label>
  <input type="number" asp-for=@Model.Duration>
  <br>

  <label>Duration</label>
  <input type="text" asp-for=@Model.Level>
  <br>

  <button type="submit">Submit</button>
</form>

CourseController.cs

using ASP_App1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP_App1.Controllers
{
    public class CourseController : Controller
    {
        public ActionResult Course() => View(new Course());

        [HttpPost]
        public ActionResult Course(Course course) => View(course);
    }
}

Ex 4-2 Working With HTTP POST

VehicleController.cs

using ASP_App1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP_App1.Controllers                      //DO NOT change the namespace name
{
    public class VehicleController : Controller
    {
        public ActionResult Registration() => View(new Registration());

        [HttpPost]
        public ActionResult Registration(Registration r)
        {
            ViewBag.CustomerName = r.CustomerName;
            ViewBag.VehicleNo = r.VehicleNo;
            ViewBag.PhoneNumber = r.PhoneNumber;
            ViewBag.City = r.City;

            return View("./Confirm");
        }
    }
}

Registration.cshtml

@model ASP_App1.Models.Registration

<h1><u>One Stop Service</u></h1>

<form action="POST">
  <label for="CName">Customer Name</label>
  <input type="text" id="CName" asp-for=@Model.CustomerName>
  <br>

  <label for="Pno">Phone Number</label>
  <input type="number" id="Pno" asp-for=@Model.PhoneNumber>
  <br>

  <label for="Vno">Vehical Number</label>
  <input type="text" id="Vno" asp-for=@Model.VehicleNo>
  <br>

  <label for="city">City</label>
  <input type="text" id="city" asp-for=@Model.City>
  <br>

  <label for="VModel">Vehical Model</label>
  <input type="text" id="VModel" asp-for=@Model.VehicleModel>
  <br>

  <label for="SType">Service Type</label>
  <input type="radio" name="Stype" id="Stype" value="Regular"> Regular
  <input type="radio" name="Stype" id="Stype" value="Other"> Others
  <br>

  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
</form>

Confirm.cshtml

<section>
  <h2>Welcome</h2>

  <br>
  <br>

  <p>
    <strong>Your booking for vehical Number, @ViewBag.VehicleNo was confirmed.</strong>
  </p>

  <p>
    <strong>Our service adviser (@ViewBag.City) will call you in
      Phone Number: @ViewBag.PhoneNumber</strong>
  </p>
</section>

Registration.cs

//THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASP_App1.Models
{
    public class Registration
    {
        public String CustomerName { get; set; }
        public long PhoneNumber { get; set; }
        public string VehicleNo { get; set; }
        public string City { get; set; }
        public string VehicleModel { get; set; }
        public string ServiceType { get; set; }
    }
}

Ex 6-2 Entity Framework Integration With ASP MVC

StudentController.cs

using ASP_EF_App1.DAL;
using ASP_EF_App1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP_EF_App1.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Placement()
        {
            /**  DO NOT REMOVE THE BELOW 2 LINES **/
            StudentDAO sd = new StudentDAO();
            sd.AddPlacements();
            /**   END OF 2 LINES  **/

            using (var context = new CollegeContext())
            {
                var placements = context.Placements.OrderBy(p => p.PlacementId).ToList();
                return View(placements);
            }
        }
    }
}

CollegeContext.cs

using ASP_EF_App1.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ASP_EF_App1.DAL
{
    public class CollegeContext : DbContext
    {
        public DbSet<Placement> Placements { get; set; }

        public CollegeContext() : base("CollegeContext") { }
    }
}

Placement.cs

//THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASP_EF_App1.Models
{
    public class Placement
    {
        public int PlacementId { get; set; }
        public int StudentId { get; set; }
        public String StudentName { get; set; }
        public String Company { get; set; }
        public String PlacementYear { get; set; }
    }
}

Placement.cshtml

@model IEnumerable<ASP_EF_App1.Models.Placement>

<h1>Student Placement Details</h1>

<table>
  <thead>
    <tr>
      <th>Placement Id</th>
      <th>Student Id</th>
      <th>Student Name</th>
      <th>Company</th>
      <th>Placement Year</th>
    </tr>
  </thead>
  <tbody>
    @foreach (var p in Model)
    {
      <tr>
        <td>@p.PlacementId</td>
        <td>@p.StudentId</td>
        <td>@p.StudentName</td>
        <td>@p.Company</td>
        <td>@p.PlacementYear</td>
      </tr>
    }
  </tbody>
</table>

Ex 6-3 Entity Framework Integration With ASP MVC – POST

StudentController.cs

using ASP_EF_App1.DAL;
using ASP_EF_App1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP_EF_App1.Controllers   //DO NOT change the namespace name
{
    public class StudentController : Controller     //DO NOT change the class name
    {

        public ActionResult Index()
        {
            var student = new Student
            {
                StudentName = "Johana",
                Department = "Art",
                PhoneNumber = 9876565434,
                EnrolledDate = Convert.ToDateTime("06/25/2018")
            };

            return RedirectToAction(nameof(AddDetail), student);
        }

        public ActionResult AddDetail(Student student)
        {
            using (var context = new CollegeContext())
            {
                context.Students.Add(student);
                context.SaveChanges();
            }

            return View("ViewDetails", student);
        }

    }
}

CollegeContext.cs

using ASP_EF_App1.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ASP_EF_App1.DAL
{
    public class CollegeContext : DbContext
    {
        public DbSet<Student> Students { get; set; }

        public CollegeContext() : base("CollegeContext") { }
    }
}

Student.cs

//THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASP_EF_App1.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public String StudentName { get; set; }
        public DateTime EnrolledDate { get; set; }
        public String Department { get; set; }
        public long PhoneNumber { get; set; }
    }
}

ViewDetails.cshtml

@model ASP_EF_App1.Models.Student

<table>

  <tr>
    <td>StudentName</td>
    <td>
      <b>@Model.StudentName</b>
    </td>
  </tr>

  <tr>
    <td>Department</td>
    <td>
      <b>@Model.Department</b>
    </td>
  </tr>

  <tr>
    <td>PhoneNumber</td>
    <td>
      <b>@Model.PhoneNumber</b>
    </td>
  </tr>

  <tr>
    <td>EnrolledDate</td>
    <td>
      <b>@Model.EnrolledDate</b>
    </td>
  </tr>
</table>

Ex 6-4 Entity Framework Integration With ASP – POST

Project.cs

//THIS IS FOR REFERENCE ONLY. YOU ARE NOT REQUIRED TO MAKE ANY CHANGES HERE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASP_EF_App1.Models
{
    public class Project
    {
        public int ProjectId { get; set; }
        public String ProjectName { get; set; }
        public String Platform { get; set; }
        public String Client { get; set; }
        public int Duration { get; set; }
    }
}

ProjectController.cs

using ASP_EF_App1.DAL;
using ASP_EF_App1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ASP_EF_App1.Controllers
{
    public class ProjectController : Controller
    {
        public ActionResult ProjectDetail() => View("AddProjectDetails");

        [HttpPost]
        public ActionResult ProjectDetail(Project project)
        {
            project.ProjectId = 1;
            using (var context = new ProjectContext())
            {
                context.Projects.Add(project);
                context.SaveChanges();
            }

            return View("ViewProjectDetails", project);
        }
    }
}

ProjectContext.cs

using ASP_EF_App1.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ASP_EF_App1.DAL        //DO NOT change the namespace name
{
    public class ProjectContext : DbContext        //DO NOT change the class name
    {
        public DbSet<Project> Projects { get; set; }

        public ProjectContext() : base("ProjectDB")
        { }
    }
}

AddProjectDetails.cshtml

@model ASP_EF_App1.Models.Project

@using (Html.BeginForm("ProjectDetail", "Project", FormMethod.Post))
{
  @Html.LabelFor(m=>m.ProjectName) @Html.TextBoxFor(m=>m.ProjectName)
  @Html.LabelFor(m=>m.Platform) @Html.TextBoxFor(m=>m.Platform)
  @Html.LabelFor(m=>m.Client) @Html.TextBoxFor(m=>m.Client)
  @Html.LabelFor(m=>m.Duration) @Html.TextBoxFor(m=>m.Duration)

  <button id="submit" type="submit">Submit</button>
}

ViewProjectDetails.cshtml

@model ASP_EF_App1.Models.Project

<table>
  <tr>
    <td>ProjectId</td>
    <td><b>@Model.ProjectId</b></td>
  </tr>

  <tr>
    <td>ProjectName</td>
    <td><b>@Model.ProjectName</b></td>
  </tr>

  <tr>
    <td>Platform</td>
    <td><b>@Model.Platform</b></td>
  </tr>

  <tr>
    <td>Client</td>
    <td><b>@Model.Client</b></td>
  </tr>

  <tr>
    <td>Duration</td>
    <td><b>@Model.Duration</b></td>
  </tr>
</table>

Similar Posts