MVC Material
MVC Material
MVC stands for model-view-controller. MVC is a pattern for developing applications that are well architected, testable and
easy to maintain. MVC-based applications contain:
M odels: Classes that represent the data of the application and that use validation logic to enforce business rules for
that data.
V iews: Template files that your application uses to dynamically generate HTML responses.
C ontrollers: Classes that handle incoming browser requests, retrieve model data, and then specify view templates that
return a response to the browser.
Let's begin by creating a controller class. In Solution Explorer, right-click the Controllers folder and then click Add,
then Controller.
The controller methods will return CSHTML Page as an example. The controller is named HomeController and the first
method is named Index . Let's invoke it from a browser. Run the application (press F5 or Ctrl+F5). In the browser, append
"Home" to the path in the address bar. (For example, in the illustration below, it's http://localhost:1234/Home. )
The page in the browser will look like the following screenshot. In the method above, the code returned a string directly. You
told the system to just return some HTML, and it did!
ASP.NET MVC invokes different controller classes (and different action methods within them) depending on the incoming
URL. The default URL routing logic used by ASP.NET MVC uses a format like this to determine what code to invoke:1
/[Controller]/[ActionName]/[Parameters]
The first part of the URL determines the controller class to execute. So /Home maps to the HomeController class. The
second part of the URL determines the action method on the class to execute. So /HelloWorld/Index would cause
the Index method of the HomeController class to execute. Notice that we only had to browse to /Home and
the Index method was used by default. This is because a method named Index is the default method that will be called
There are various ways to pass data from a Controller to a View. I'm going to discuss how Controllers interact with Views and specifically
cover ways you can pass data from a Controller to a View to render a response back to a client. So, let's get started.
ViewBag
ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was
added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary. Let's see how it is used.
Using ViewModel we can also pass the data from the Controller to View; let's look at the image.
Step 1:
Create View:
Here @model is variable which going to get the value from controller. Which is of type
Webapplication13.Model.Employee
@model IEnumerable<WebApplication13.Models.Employee>
Action Result In Mvc
In ASP.NET, MVC has different types of Action Results. Each action result returns a different format of output. A programmer uses different
action results to get expected output. Action Results return the result to view the page for the given request.
Definition
Action Result is a result of action methods or return types of action methods. Action result is an abstract class. It is a base class for all type of
action results.
ActionResult
View Result
Partial View Result
Redirect Result
Redirect To Action Result
Redirect To Route Result
Json Result
File Result
Content Result
View Result
View result is a basic view result. It returns basic results to view page. View result can return data to view page through which class is
defined in the model. View page is a simple HTML page. Here view page has “.cshtm” extension.
View Result is a class and is derived from “ViewResultBase” class. “ViewResultBase” is derived from Action Result. View Result base class
is an Action Result. Action Result is a base class of different action result.
View Result class is inherited from Action Result class by View Result Base class. The ScreenShort
shown above describes inheritance of Action Results.
Partial View Result is returning the result to Partial view page. Partial view is one of the views that we can call inside Normal view page.
We should create a Partial view inside shared folder, otherwise we cannot access the Partial view. The diagram is shown above the Partial
view page and Layout page because layout page is a Partial view. Partial View Result class is also derived from Action Result.
Redirect Result
Redirect result is returning the result to specific URL. It is rendered to the page by URL. If it gives wrong URL, it will show 404 page errors.
Redirect to Action result is returning the result to a specified controller and action method. Controller name is optional in Redirect to Action
method. If not mentioned, Controller name redirects to a mentioned action method in current Controller. Suppose action name is not
available but mentioned in the current controller, then it will show 404 page error.
Json Result
Json result is a significant Action Result in MVC. It will return simple text file format and key value pairs. If we call action method, using Ajax,
it should return Json result.
File Result
File Result returns different file format view page when we implement file download concept in MVC using file result. Simple examples for file
result are shown below:
Content Result
Content result returns different content's format to view. MVC returns different format using content return like HTML format, Java Script
format and any other format.
Crud Operation Using Ado.net in MVC.
STEP1
Step2:
using System.Data;
using System.Data.SqlClient;
EmpId=Convert.ToInt32(dr["empid"]),
EmpName =(dr["empname"].ToString()),
EmpSalary = Convert.ToInt32(dr["empsalary"]),
}
);
}
return objlist;
}
Step3:
Create Table:
Create Procedure:
As
BEGIN
SELECT * FROM Employeedetails
END
Add Controller:
return View(EmployeeDetail);
}
Add View:
@model IEnumerable<WebApplication13.Models.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create Employee Details","Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.EmpId)
</th>
<th>
@Html.DisplayNameFor(model => model.EmpName)
</th>
<th>
@Html.DisplayNameFor(model => model.EmpSalary)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmpId)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmpName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmpSalary)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.EmpId }) |
@Html.ActionLink("Details", "Details", new { id=item.EmpId }) |
@Html.ActionLink("Delete", "Delete", new id=item.EmpId })
</td>
</tr>
}
</table>
Step1:
cmd.Parameters.AddWithValue("@empname", EmpName);
cmd.Parameters.AddWithValue("@empsalary", EmpSalary);
object i = cmd.ExecuteScalar();
int result = Convert.ToInt32(i);
return result;
[HttpGet]
public ActionResult Create()
{
return View();
}
For Post Method you can use Two operation Either FormCollection Class or Employee Class
[HttpPost]
public ActionResult Create(FormCollection formKey)
{
string empName = formKey["Name"];
int empSalary = Convert.ToInt32(formKey["Salary"]);
OR
[HttpPost]
public ActionResult Create(Employee Empobj)
{
string empName = Empobj.EmpName;
int empSalary = Convert.ToInt32(Empobj.EmpSalary);
FormCollection is a Class Which will catch all form values By Html Contol Name Property.
HttpPost Create Method will be Executed When User Click on Submit Button
@model WebApplication13.Models.Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Add Procedure:
return View(obj);
}
AddView:
CREATE PROCEDURE [dbo].[spr_updateEmployeeDetails]
@empid int,
@empname nvarchar(50),
@empsalary int
AS
BEGIN
update employeeDetails set empname=@empname,empsalary=@empsalary where empid=@empid
END
con.Open();
int i = cmd.ExecuteNonQuery();
return i;
[HttpPost]
public ActionResult Edit(Employee obj)
{
int result = dbobj.updateEmployeeDetails(obj);
if (result > 0)
{
return RedirectToAction("Index");
}
else {
return View(obj);
}
}
}
@model WebApplication13.Models.Employee
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.EmpId, htmlAttributes: new { @class = "control-
label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmpId, new { htmlAttributes = new { @class
= "form-control" } })
@Html.ValidationMessageFor(model => model.EmpId, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EmpName, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmpName, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.EmpName, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EmpSalary, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmpSalary, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.EmpSalary, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Asp.net with Entity Framework Approach.
Entity Framework is an open-source ORM framework for .NET applications supported by Microsoft. It enables
developers to work with data using objects of domain specific classes without focusing on the underlying database
tables and columns where this data is stored. With the Entity Framework, developers can work at a higher level of
abstraction when they deal with data, and can create and maintain data-oriented applications with less code
compared with traditional applications.
Official Definition: “Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work
with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually
need to write.”
Modelling: EF (Entity Framework) creates an EDM (Entity Data Model) based on POCO (Plain Old CLR
Object) entities with get/set properties of different data types. It uses this model when querying or saving
Querying: EF allows us to use LINQ queries (C#/VB.NET) to retrieve data from the underlying database.
The database provider will translate this LINQ queries to the database-specific query language (e.g. SQL
for a relational database). EF also allows us to execute raw SQL queries directly to the database.
Change Tracking: EF keeps track of changes occurred to instances of your entities (Property values)
Saving: EF executes INSERT, UPDATE, and DELETE commands to the database based on the changes
occurred to your entities when you call the SaveChanges() method. EF also provides the
Concurrency: EF uses Optimistic Concurrency by default to protect overwriting changes made by another
Transactions: EF performs automatic transaction management while querying or saving data. It also
Caching: EF includes first level of caching out of the box. So, repeated querying will return data from the
Built-in Conventions: EF follows conventions over the configuration programming pattern, and includes
Configurations: EF allows us to configure the EF model by using data annotation attributes or Fluent API
Manager Console or the Command Line Interface to create or manage underlying database Schema.
Database First
If you already have a database, the Entity Framework designer built into Visual Studio can automatically
generate a data model that consists of classes and properties that correspond to existing database objects
such as tables and columns. The information about your database structure (store schema), your data model
(conceptual model), and the mapping between them is stored in XML in an .edmx file. The Entity
Framework designer provides a graphical UI that you can use to display and edit the .edmx file.
Model First
If you don't have a database yet, you can begin by creating a model in an .edmx file by using the Entity
Framework graphical designer in Visual Studio. When the model is finished, the Entity Framework
designer can generate DDL (data definition language) statements to create the database. As in Database
First, the .edmx file stores model and mapping information.
Code First
Whether you have an existing database or not, you can use the Entity Framework without using the
designer or an .edmx file. If you don't have a database, you can code your own classes and properties that
correspond to tables and columns. If you do have a database, Entity Framework tools can generate the
classes and properties that correspond to existing tables and columns. The mapping between the store
schema and the conceptual model represented by your code is handled by convention and by a special
mapping API. If you let Code First create the database, you can use Code First Migrations to automate the
process of deploying the database to production. Migrations can also automate the deployment of database
schema changes to production when your data model changes.
Choose Code First for new development unless you want to use a graphical designer to model database
objects and relationships. The Entity Framework designer only works with Database First and Model First.
Before you choose Database First or Model First, however, consider how you want to handle updates to the
data model after you create the database, and how you want to deploy the database and deploy updates to it.
Code First Migrations automates the process of implementing and deploying database schema changes that
result from data model changes. The advantages of Code First Migrations might outweigh the advantages
of the Entity Framework designer.
Let us see all this by using Enitity Framework Database Approach:
For database approach using EnitityFramework you need to have Existing Database.
Employee Database is Approach given below.
Step1:
Entity Framework EmployeeFramework Edmx. Will be Created.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
1)EmployeeModel.Context.Cs
namespace WebApplication13.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace WebApplication13.Models
{
using System;
using System.Collections.Generic;
</ connectionStrings>
So till Now what we have done is we just Created EntityFramework Now we will add
Controller.
EmployeeDetailsController with Predefined code for crud operation and View Will be
Created (insert,delete,update)
// GET: employeeDetails
public ActionResult Index() this code will reterive data in form list
{
return View(db.employeeDetails.ToList());Tolist will Convert data of Table to List
}
Showing all Data.
// GET: employeeDetails/Details/5
public ActionResult Details(int? id)(It is used to display Single Detail)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
employeeDetail employeeDetail = db.employeeDetails.Find(id);
if (employeeDetail == null)
{
return HttpNotFound();
}
return View(employeeDetail);
}
View:
// GET: employeeDetails/Create
public ActionResult Create()//this Method Load Create Page
{
return View();
}
// POST: employeeDetails/Create
// To protect from overposting attacks, please enable the specific properties you
want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "empid,empname,empsalary")]
employeeDetail employeeDetail) //When you Click button total form will be post and get
values in employeeDetail variable.
employeeDetail.Empid=1;
employeeDetail.EmpName=”xyz”;
{
if (ModelState.IsValid) employeeDetail.Salary=1234;
{
db.employeeDetails.Add(employeeDetail); employeeDetail add to employeeDetails table
db.SaveChanges();//permenantely Saving Data.
return RedirectToAction("Index");
}
return View(employeeDetail);
}
View :
// GET: employeeDetails/Edit/5
public ActionResult Edit(int? id)//When we Click Edit Button u will get value in Id
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
employeeDetail employeeDetail = db.employeeDetails.Find(id);//based on Id finding Record
if (employeeDetail == null)
{ It will send to edit view so that in that textbox we will get
return HttpNotFound();
values.
}
return View(employeeDetail);
}
// POST: employeeDetails/Edit/5
// To protect from overposting attacks, please enable the specific properties you
want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "empid,empname,empsalary")]
employeeDetail employeeDetail)
{
if (ModelState.IsValid)
{
db.Entry(employeeDetail).State = EntityState.Modified;
db.SaveChanges();//Updating table Values using savechanges method.
return RedirectToAction("Index");
}
return View(employeeDetail);
}
// GET: employeeDetails/Delete/5
public ActionResult Delete(int? id)//Load single Record and display Delete View
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
employeeDetail employeeDetail = db.employeeDetails.Find(id);
if (employeeDetail == null)
{
return HttpNotFound();
}
return View(employeeDetail);
}
// POST: employeeDetails/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
employeeDetail employeeDetail = db.employeeDetails.Find(id);
db.employeeDetails.Remove(employeeDetail);//By using Remove Method DeletingRecord
db.SaveChanges();
return RedirectToAction("Index");
}
View :
We have Seen
@model WebApplication13.Models.employeeDetail
@model variable which will be present top in a view .it is used to store single employee
Record
@model IEnumerable<WebApplication13.Models.employeeDetail>
Here by using database approach Entity framework will create Controller and View
Automatically.
Step 1:
It’s required typecasting for getting data and check for null values to avoid error.
Viewdata is used for transferring the data from controller to view for a corresponded or
single request
obj.Add("pratiusha");
obj.Add("deepti");
obj.Add("Nagini");
obj.Add("Anusha");
ViewData["Student"] = obj;
return View();
<ul>
<li>@item</li>
}
</ul>
2)ViewBag:
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
Basically it is a wrapper around the ViewData and also used to pass data from controller
to corresponding view.
}
--->
creating Controller
emp.Empid = 1;
emp.EmpName = "prfatiusha";
emp.Department = "IT";
ViewBag.Details = emp;
return View();
under view
<ul>
<li> @ViewBag.Details.Empid</li>
<li> @ViewBag.Details.EmpName</li>
<li> @ViewBag.Details.Department</li>
</ul>
or
@{
ViewBag.Title = "Index";
<h2>Index</h2>
<ul>
<li> @myfellow.Empid</li>
<li> @myfellow.EmpName</li>
<li> @myfellow.Department</li>
</ul>
TempData:
TempData is a dictionary object that is derived from TempDataDictionary class and stored
in short lives session.
TempData is used to pass data from current request to subsequent request (means
redirecting from one page to another).
It’s life is very short and lies only till the target view is fully loaded.
It’s required typecasting for getting data and check for null values to avoid error.
It is used to store only one time messages like error messages, validation messages. To
persist data with TempData refer this article: Persisting Data with TempData
TempData:it is used to transfer the data from one controller to another controller then
you can use tempdata
Tempdata["key"]=value;
Tempdata.keep();
2)peek method:
it is used for getting the object by using the key and will retain the values
TempData["Student"] = "Pratiusha";
return RedirectToAction("About");
var b = TempData.Peek("Student");
var c = TempData.Peek("Student");
ViewData["b"] = b;
ViewData["c"] = c;
return View();
Session is very well known concept in any web application. It is used to pass data from page to page. Basically web
application is stateless in nature. So, to maintain state across request and response we need to use few technique, Session
is one of them.
Using session variable we can pass data from model to controller or controller to view.
Create Model:
namespace MVC3.Models
Create Controller:
namespace MVC3.Controllers
Obj.Surname = "Santosh";
Session["Customer"] = Obj;
return View();
Within controller we are creating object of model class(Customer) and populating with data. Then we are inserting object
of customer class within session variable.
<div>
@{
<br />
</div>
Html.Beginform
Html.EndForm
Html.Label
Html.TextBox
Html.TextArea
Html.Password
Html.DropDownList
Html.CheckBox
Html.RedioButton
Html.ListBox
Html.Hidden
Below are Strongly Type Html Helper methods, this will allow us to check compile time errors. We get Model's Property intelligence at
Runtime.
Html.LabelFor
Html.TextBoxFor
Html.TextAreaFor
Html.DropDownListFor
Html.CheckBoxFor
Html.RadioButtonFor
Html.ListBoxFor
Html.HiddenFor
Html helpers
TextBox:
@Html.Label("Username")
@Html.TextBox("txtUsername","pratiusha",new { @class="mytest", @readonly="true"})<br/>
Password:
<label>Password:</label>
@Html.Password("txtpwd")<br />
RadioButton
<label>Gender</label>
@Html.RadioButton("rbgender","Male",true)<span>Male</span>
@Html.RadioButton("rbgender", "Female")<span>Female</span><br />
CheckBox
<label>Choose Courses</label>
@Html.CheckBox("dotnet")<span>Dotnet</span>
@Html.CheckBox("Java")<span>Java</span><br />
DropdownList
<label>Select Country</label>@Html.DropDownList("Country",new List<SelectListItem>()
{
new SelectListItem {Text="India",Value="1" },
new SelectListItem {Text="China",Value="2",Selected=true},
new SelectListItem {Text="Bangladesh",Value="3" }
TextArea:
<label>Comments</label> @Html.TextArea("comments",null,5,10,null)
FileUpload Control
@using (Html.BeginForm("Index","Home",FormMethod.Post,new {enctype="multipart/form-
data"}))
{
<span>File</span>
<input type="file" id="fileupload" name="fileupload" />
<input type="submit" value="upload" />
}
@ViewBag.msg
return View();
}
@myhtmlhelper.MyLabel("pratiusha")
@Html.createUrControl("file")
using System.Web.Mvc;
namespace HtmlHelpersExample.CustomHelpers
{
public static class myhtmlhelper
{
public static IHtmlString MyLabel(string content)
{
string htmlstring = String.Format("<label>{0}</label>", content);
return new HtmlString(htmlstring);
}
CheckboxList in Mvc
Step1:
Step2:
Add Controller:
[httpGet]
new EmployeeModel{Id=1,Name=”dinkar”,Checked=false},
new EmployeeModel{Id=2,Name=”salman”,Checked=false},
new EmployeeModel{Id=3,Name=”santosh”,Checked=false},
}
return View(list);
[HttpPost]
return View(liobj);
@model WebHelper.Models.Register
@{
<SelectListItem>(){
new SelectListItem(){Value="1",Text="India"},
new SelectListItem(){Value="2",Text="UK"}
};
<br />
<br />
<br />
@Html.Label("Male")
@Html.Label("Female")
<br />
<br />
@Html.LabelFor(m => m.Terms)
<br />