MVC Tutorials
·
Models: Model objects are the parts of the application
that implement the domain logic. Often, model objects also retrieve and store
model state in a database.
·
Views: Views are the components that display the
application's user interface (UI). Typically, this UI is created from the model
data. An example would be the edit view of Albums that displays text boxes and
a drop-down list based on the current state of an Album object.
·
Controllers: Controllers are the components that handle
user interaction, manipulate the model, and ultimately select a view to render
the UI. In an MVC application, the view only displays information; the
controller handles and responds to user input and interaction.
Start page setting in _ViewStart.cshtml
in Views folder
@{
// Set the layout page for the whole site
Layout = "~/Shared/Layout.cshtml";
}
// Set the layout page for the whole site
Layout = "~/Shared/Layout.cshtml";
}
Eg:- @{
Layout = "~/Views/Shared/Index.cshtml";
}
1. Main
Folders
·
Controllers- for storing
controllers
·
Models-for storing
models
·
Views-for storing views
·
App_Data - for storing
databases and data files
·
Content/Images - for
storing images
·
Scripts - for storing
browser scripts
·
Views/Shared - for
storing shared style and layout files
2. Database Connection and management in Models
Creating the Model
On the Models folder, right click and create a new
class by clicking on Add -> Class.
Example:-
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
using
System.ComponentModel.DataAnnotations;
using
connectionClass;
namespace
CabAutomationSystem.Models
{
public class Country
{
connectionClass.connectionClass cs = new
connectionClass.connectionClass();
public string conStr = ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString();
SqlConnection
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString());
public int id { get; set; }
[Required(ErrorMessage
= "Country is required")]
[Display(Name
= "Country:")]
public string country { get;
set; }
public DataSet GetAllCountry()
{
SqlCommand
cmd = new SqlCommand("select id,cntry from cntry order by id",
cn);
DataSet ds
= new DataSet();
SqlDataAdapter
da = new SqlDataAdapter(cmd);
da.Fill(ds);
return
ds;
}
public int Insert(string
country)
{
Int64
id = cs.GenerateId("cntry", "id", conStr);
SqlCommand
cmd = new SqlCommand("insert into cntry(id,cntry) values('" +
id + "','" + country + "')", cn);
cn.Open();
return
cmd.ExecuteNonQuery();
}
public int Update(string
country, int
id)
{
SqlCommand
cmd = new SqlCommand("Update cntry Set cntry='" + country + "' Where id=" + id, cn);
cn.Open();
return
cmd.ExecuteNonQuery();
}
public int Delete(int id)
{
SqlCommand
cmd = new SqlCommand("Delete From cntry Where id=" + id, cn);
cn.Open();
return
cmd.ExecuteNonQuery();
}
}
}
3. User interaction management and model
manipulation in Controllers
Creating our
Controller
Right
click on the Controllers folder
and select Add -> Controller.
Example:-
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
using
CabAutomationSystem.Models;
using
CabAutomationSystem.DatabaseContext;
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
using
System.ComponentModel.DataAnnotations;
using
connectionClass;
namespace
CabAutomationSystem.Controllers
{
public class AdminController
: Controller
{
connectionClass.connectionClass cs = new
connectionClass.connectionClass();
public string conStr = ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString();
SqlConnection
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString());
#region ManageCountry
public ActionResult
ManageCountry(CabAutomationSystem.Models.Country
CountryList)
{
DataSet
ds = CountryList.GetAllCountry();
ViewBag.AuthorList = ds.Tables[0];
return
View();
}
[HttpGet]
public ActionResult AddCountry()
{
return
View();
}
[HttpPost]
public ActionResult
AddCountry(CabAutomationSystem.Models.Country
countryinsert)
{
if
(ModelState.IsValid)
{
int
_records = countryinsert.Insert(countryinsert.country);
if
(_records > 0)
{
return
RedirectToAction("ManageCountry", "Admin");
}
else
{
ModelState.AddModelError("", "Can
Not Insert");
}
}
return
View(countryinsert);
}
[HttpGet]
public ActionResult EditCountry(int
id, CabAutomationSystem.Models.Country
countryupdate)
{
SqlCommand
cmd = new SqlCommand("select id,cntry from cntry where id=" +
id, cn);
cn.Open();
SqlDataReader
dr = cmd.ExecuteReader();
if
(dr.Read())
{
countryupdate.id = Convert.ToInt32(dr["id"].ToString());
countryupdate.country = dr["cntry"].ToString();
}
else
{
dr.Close();
}
dr.Close();
cn.Close();
return
View(countryupdate);
}
[HttpPost]
public ActionResult
EditCountry(CabAutomationSystem.Models.Country
countryupdate, FormCollection form, int id)
{
if
(ModelState.IsValid)
{
int
_records = countryupdate.Update(countryupdate.country, id);
if
(_records > 0)
{
return
RedirectToAction("ManageCountry", "Admin");
}
else
{
ModelState.AddModelError("", "Can
Not Update");
}
}
return
View(countryupdate);
}
public ActionResult DeleteCountry(int id, CabAutomationSystem.Models.Country
countrydelete)
{
int
records = countrydelete.Delete(id);
if
(records > 0)
{
return
RedirectToAction("ManageCountry", "Admin");
}
else
{
ModelState.AddModelError("", "Can
Not Delete");
return
View("ManageCountry");
}
// return
View("Index");
}
#endregion ManageCountry
}
}
4. User Interface Management in Views
Example:-
v Right click on “ManageCountry” in Controller and create view “ManageCountry.cshtml”
@model CabAutomationSystem.Models.Country
@{
ViewBag.Title = "ManageCountry";
Layout = "~/Views/Admin/Master.cshtml";
}
<h2>ManageCountry</h2>
<div>
@Html.ActionLink("Add
Country", "AddCountry")
<br />
<table border="1" style="border-color:LightSkyBlue;border-bottom-style:double">
<tr>
<td></td>
<td></td>
<td style="background-color: #800080; color: #FFFFFF; font-family: 'Times New
Roman', Times, serif;
font-size: large; border-style: inset; border-width: thin">Country</td>
</tr>
@foreach
(System.Data.DataRow dr in ViewBag.AuthorList.Rows)
{
<tr>
<td>
@Html.ActionLink("Edit",
"EditCountry", new { id = dr["id"].ToString()
})
</td>
<td>
@Html.ActionLink("Delete",
"DeleteCountry", new { id = dr["id"].ToString()
})
</td>
<td>
@dr["cntry"].ToString()
</td>
</tr>
}
</table>
</div>
v Right click on “AddCountry” in Controller and create view “AddCountry.cshtml”
@model CabAutomationSystem.Models.Country
@{
ViewBag.Title = "AddCountry";
Layout = "~/Views/Admin/Master.cshtml";
}
<body>
<h1>Add
New Country</h1>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true,
"Insertion was unsuccessful. Please correct
the errors and try again.")
<div>
<fieldset>
<legend>Country
Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.country)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.country)
@Html.ValidationMessageFor(m =>
m.country)
</div>
<p>
<input type="submit" value="Insert" />
</p>
</fieldset>
</div>
}
</body>
v Right click on “EditCountry” in Controller and create view “EditCountry.cshtml”
@model CabAutomationSystem.Models.Country
@{
ViewBag.Title = "EditCountry";
Layout = "~/Views/Admin/Master.cshtml";
}
<body>
<h1>Edit
Country</h1>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true,
"Insertion was unsuccessful. Please correct
the errors and try again.")
<div>
<fieldset>
<legend>Country
Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.country)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.country)
@Html.ValidationMessageFor(m =>
m.country)
</div>
<p>
<input type="submit" value="Update" />
</p>
</fieldset>
</div>
}
</body>
5. Master.cshtml in Views
<!DOCTYPE
html>
<html>
<head>
<title></title>
<link href="@Url.Content("~/Content/admin_style.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/Mystyle.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="top">
<div class=""></div>
<div class="contact">
<p>
</p>
</div>
</div>
<input id="hdndranch" runat="server" type="hidden" />
<div>
<div>
<div id="ConetntAreaContainer" class="clear">
<table style="width: 100%" width="100%">
<tr>
<td style="width: 20%" valign="top">
<table cellpadding="6" cellspacing="3" width="100%" style="background-color: #996633">
<tr>
<td style="width: 8px">
</td>
<td height="10">
</td>
</tr>
<tr >
<td style="width: 8px">
<img src="../../Content/images/arrow_doublebl.jpg"
/></td>
<td>
@*@Html.ActionLink("Home", "Home",
"Admin", new { @class = "ad_link" })*@
@Html.ActionLink("Home", "Home",
"Admin")
</td>
</tr>
<tr id="tr3" runat="server">
<td style="width: 8px">
<img src="../../Content/images/arrow_doublebl.jpg"
/></td>
<td>
@Html.ActionLink("ManageCountry", "ManageCountry", "Admin")
</td>
</tr>
<tr id="tr49" runat="server">
<td style="width: 8px">
<img src="../../Content/images/arrow_doublebl.jpg"
/></td>
<td>
@Html.ActionLink("Logout", "Logout",
"Admin", new
{ @class = "ad_link" })
</td>
</tr>
</table>
</td>
<td style="width: 80%" valign="top">
<div id="ContentContainer" style="width:75%">
<div id="Welcomecontent">
<p>
<br />
@RenderBody()
<br />
</p>
</div>
</div>
</td>
</tr>
</table>
<div style="clear:both"></div>
</div>
<div id="FooterConatiner" style="height:25px"></div>
</div>
</div>
</body>