MVC :
Model-View-Controller (MVC) is architectural pattern separates an
application into three main components:
·
Model
·
View
·
Controller
MVC
framework is a lightweight, highly testable presentation framework and integrated with existing ASP.NET features,
such as master pages and membership-based authentication.
For
development user can user either MVC
approach or combine approach with Asp.net Applications
Namespace
used for MVC is System.Web.Mvc
Components of MVC :
Model
: Model object contain application or business logic e.g. Database
operations handle through model.
View : Views are the components that display
the user interface (UI) created from the
model data.
Controller: This
handle user interaction and work
with model. e.g. accept Query string values and pass to model and result
retrieved from model pass to view to display. so controller works with both
model and view.
Features of MVC Framework
1.
Separation of
application tasks (input logic, business logic, UI logic)
2.
The ASP.NET MVC
framework uses the ASP.NET routing engine, which provides flexibility for
mapping URLs to controller classes. You can define routing rules that the
ASP.NET MVC framework uses in order to evaluate incoming URLs and to select the
appropriate controller.
3.
Support for using
the markup in existing ASP.NET page (.aspx files), user control (.ascx files),
and master page (.master files) markup files as view templates.
4.
Support for
existing ASP.NET features. Eg : authorization,membership,
roles,caching etc
5.
ASP.NET MVC
framework does not use the ASP.NET Web
Forms postback model for interactions with the server. Instead, all
end-user interactions are routed to a controller class.
MVC project Structure :
·
References: It contains all dll references
·
Content
: It contains files such as cascading
style sheet files, images, and so on.
·
Controllers:
It contains controller components. The MVC framework requires the names of all
controllers to end with "Controller
e.g. HomeController.
·
Models:
it contains classes that represent the application model for your MVC Web
application. It includes code that
defines objects and that defines the logic for interaction with the data store.
·
Scripts
: It contains javascript files like
jquery files etc.
·
Views, It contains all view components . Views use ViewPage
(.aspx), ViewUserControl (.ascx), and ViewMasterPage (.master) files, in
addition to any other files that are related to rendering views.
The Views folder contains a folder for each controller; the folder
is named with the controller-name prefix.
For example, if you have a controller named HomeController,
the Views folder contains a folder named Home.
By default, when the
ASP.NET MVC framework loads a view, it looks for a ViewPage (.aspx) file that
has the requested view name in the Views\controllerName
folder.
By default, there is also a folder named Shared in the Views
folder, which does not correspond to any controller.
The Shared folder is used for views that are shared across
multiple controllers. For example, you can put the Web application's master
page in the Shared folder.
Global.asax.cs file :
It define default routing logic. In this file route objects are added to the RouteTable
object
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
using
System.Web.Routing;
namespace
MvcTextApplication
{
// Note: For
instructions on enabling IIS6 or IIS7 classic mode,
// visit
http://go.microsoft.com/?LinkId=9394801
public class MvcApplication
: System.Web.HttpApplication
{
public static void
RegisterGlobalFilters(GlobalFilterCollection
filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void
RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}",
// URL with parameters
new
{ controller = "Home", action = "Index", id = UrlParameter.Optional
} // Parameter defaults
);
}
protected
void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
Add controller : ADD
NEW CONTROLLER RIGHT CLICK ON CONTROLLER FOLDER AND ADD THEN ON CONTROLLER .
Note
Controller name must end with Controller suffix e.g. HomeController
·
The controller
defines action methods.
·
Controllers can
include as many action methods as needed.
Action methods typically have a one-to-one mapping with user
interactions. When a user enters a URL into the browser, the MVC application uses routing rules that
are defined in the Global.asax file to
parse the URL and to determine the path of the controller.
The controller then determines the
appropriate action method to handle the request.
By
default, the URL of a request is treated as a sub-path that includes the controller name followed by the action name.
Example :
In this Home/Index is sub path and default routing rule treats
Home as controller (HomeController) and
treats Index and Action method
In this Home/Index is sub path and default routing rule treats
Home as controller (HomeController) and
treats Index and Action method and default value 1 is passed and parameter in
Index method
public class HomeController : Controller
{
public ActionResult
Index()
{
return View();
}
}
ActionResult Return Type :
·
View : Renders a view as a Web page.
·
PartialView
: Renders a partial view, which defines
a section of a view that can be rendered inside another view.
·
Redirect
: Redirects to another action method by
using its URL.
·
RedirectToAction
: Redirects to another action method.
·
RedirectToRoute
: Redirects to another action method
·
Content: Returns
a user-defined content type.
·
JSON:
Returns a serialized JSON object.
·
JavaScript
: Returns a script that can be executed
on the client.
·
File
: Returns binary output to write to the response.
·
EmptyResult
: Represents a return value that is used if the action method must return a null result (void).
Examples: Without LINQ and ENTITY Framework
Data Table :
USE
[FundPriceDev]
GO
/******
Object: Table [dbo].[tblfundsample] Script Date: 06/01/2012 09:24:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblfundsample](
[FundID] [int] IDENTITY(1,1) NOT NULL,
[FundName] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
insert into tblfundsample (FundName) values('Global USD1')
insert into tblfundsample (FundName) values('FPI Global EURO')
insert into tblfundsample (FundName) values('I Global GBP')
insert into tblfundsample (FundName) values('STAR Funds')
insert into tblfundsample (FundName) values('SPI VAM US Small Cap Growth
(ASO)')
insert into tblfundsample (FundName) values('US Large Cap Growth B')
insert into tblfundsample (FundName) values('US Mid Cap Growth B')
insert into tblfundsample (FundName) values('US Large Cap Growth C')
insert into tblfundsample (FundName) values('SPILA VAM Driehaus fund')
Project Structure
Model : Funds.cs Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
public class Fund
{
public int
NumberOfFunds { get; set;
} // return Number of Funds Publically
public List<string> FundsList { get;
set; } // return List of strings Publically
private int _FundID;
private string
_Fundname;
public int FundID
{
get { return _FundID;
}
set { _FundID = value;
}
}
public string
FundName
{
get { return
_Fundname; }
set { _Fundname = value;
}
}
// This function return List if string values eg :
fundNames
public List<string>
getFundsList()
{
SqlConnection Conn = new
SqlConnection("Connection
String");
Conn.Open();
SqlCommand Cmd = new
SqlCommand("Select
top 10 FundId,FundName from tblfundsample ", Conn);
SqlDataReader dr = Cmd.ExecuteReader();
Fund dc = new Fund();
List<string>
fundlist = new List<string>();
while (dr.Read())
{
fundlist.Add(dr["FundName"].ToString());
}
dr.Close();
Conn.Close();
return fundlist;
}
// This function return List of Fund Class Object values
public List<Fund> getFundsListClass()
{
SqlConnection Conn = new
SqlConnection("Connection
String");
Conn.Open();
SqlCommand Cmd = new
SqlCommand("Select
FundId,FundName from tblfundsample ", Conn);
SqlDataReader dr = Cmd.ExecuteReader();
Fund dc;
List<Fund>
fundlist = new List<Fund>();
while (dr.Read())
{
dc = new Fund();
dc.FundID = Convert.ToInt32(dr["FundId"].ToString());
dc.FundName = dr["FundName"].ToString();
fundlist.Add(dc);
}
dr.Close();
Conn.Close();
return fundlist;
}
// This function create new fund
public int
CreateFundsMethod()
{
SqlConnection Conn = new
SqlConnection("Connection
String");
Conn.Open();
SqlCommand Cmd = new
SqlCommand();
Cmd.CommandText="insert into
tblfundsample(FundName)
values(@FundName);";
Cmd.Connection = Conn;
Cmd.CommandType = CommandType.Text;
Cmd.Parameters.Add("@FundName",
SqlDbType.VarChar, 100).Value = _Fundname;
int i = Cmd.ExecuteNonQuery();
Conn.Close();
return
i;
}
// This function update new fund
public int
UpdateFunddetails()
{
SqlConnection Conn = new
SqlConnection("Connection
String");
Conn.Open();
SqlCommand Cmd = new
SqlCommand();
Cmd.CommandText = "Update tblfundsample
set FundName=@FundName where
FundID=@FundID;";
Cmd.Connection = Conn;
Cmd.CommandType = CommandType.Text;
Cmd.Parameters.Add("@FundName",
SqlDbType.VarChar).Value = _Fundname;
Cmd.Parameters.Add("@FundID",
SqlDbType.Int).Value = _FundID;
int i = Cmd.ExecuteNonQuery();
Conn.Close();
return i;
}
// This function delete fund
public int
DeleteFund()
{
SqlConnection Conn = new
SqlConnection("Connection
String");
Conn.Open();
SqlCommand Cmd = new
SqlCommand();
Cmd.CommandText = "delete from
tblfundsample where FundID=@FundID";
Cmd.Connection = Conn;
Cmd.CommandType = CommandType.Text;
Cmd.Parameters.Add("@FundID",
SqlDbType.VarChar, 100).Value = _FundID;
int i = Cmd.ExecuteNonQuery();
Conn.Close();
return i;
}
// This function get fund Name by FundID
public Fund
getFunddetailByFundID(int id)
{
SqlConnection Conn = new
SqlConnection("Connection
String");
Conn.Open();
SqlCommand Cmd = new
SqlCommand("Select
top 10 FundId,FundName from tblfundsample where FundID=" + id + "", Conn);
SqlDataReader
dr = Cmd.ExecuteReader();
Fund dc = new Fund();
while (dr.Read())
{
dc.FundID = Convert.ToInt32(dr["FundId"].ToString());
dc.FundName = dr["FundName"].ToString();
}
dr.Close();
Conn.Close();
return dc;
}
}
Controllers
:
HomeController.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
namespace MvcTextApplication.Controllers
{
public class HomeController : Controller
{
//*************************************************************
// Main action method
public ActionResult
Index()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View();
}
// HTML PART
<div>
This is my first MVC application
</div><br />
<div>
<%: ViewData["CurrentTime"]
%>
</div>
//OUTPUT :
//*************************************************************
// Second action method
public ActionResult
About()
{
ViewData["text"] = "I am user";
return View();
}
// HTML PART
<div>
<%:
ViewData["text"] %>
</div>
//OUTPUT :
//*************************************************************
// Action method with parameter
public ActionResult
Parametermethod (string id)
{
ViewData["parameter"] = "HI "
+ id.ToString();
return View();
}
// HTML PART
<div>
<%: ViewData["parameter"]%>
</div>
<hr />
<h3>About action method called</h3>
<%= Html.Action("About") %> <%--Here We are
calling onother Action Method which will display Action method About --%>
//OUTPUT :
//*************************************************************
// Action method with OPTIONAL parameter
public ActionResult
Optional(int? id)
{
if (!id.HasValue)
{
ViewData["parameter"] = "Sorry No parameter";
}
else
{
ViewData["parameter"] = "parameter value is
: " + id.ToString();
}
return View();
}
// HTML PART
<div>
<%: ViewData["parameter"]%>
</div>
//OUTPUT :
//*************************************************************
// Action method to return Fund details
public ViewResult
getFundsbysearch(int id)
{
SqlConnection Conn = new
SqlConnection("");
Conn.Open();
SqlCommand Cmd = new
SqlCommand("Select
top 10 FundId,FundName from tblfundsample where FundID=" + id + "", Conn);
SqlDataReader dr = Cmd.ExecuteReader();
Fund dc = new Fund();
while (dr.Read())
{
dc.FundID = Convert.ToInt32(dr["FundId"].ToString());
dc.FundName = dr["FundName"].ToString();
}
dr.Close();
Conn.Close();
return View("getFundsbysearch",
dc);
}
// HTML PART
<table>
<tr>
<th> Fund ID </th>
<th>Fund Name</th>
</tr>
<tr>
<td> <%= Model.FundID
%></td>
<td> <%= Model.FundName
%></td>
</tr>
</table>
url : http://localhost:59829/Home/getFundsbysearch/2 -->
where
2 is FundID
//OUTPUT :
NON action Method for Internal logic
[NonAction]
private void
NonActionmethod()
{
// Method logic.
}
}
}
More Examples : http://stephenwalther.com/archive/2009/04/13/asp-net-mvc-tip-50-ndash-create-view-models.aspx
FundsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcTextApplication.Controllers
{
public class FundsController : Controller
{
Fund dc = new Fund();
//*************************************************************
// Function to get list of funds and
show Total Number of records
public ActionResult
getFunds()
{
List<string>
fundlistnew;
fundlistnew = dc.getFundsList();
var genres = fundlistnew;
var viewModel = new Fund
{
NumberOfFunds = genres.Count(),
FundsList = genres
};
return View(viewModel);
}
// HTML PART
<b><p>
Total Funds <%: Model.NumberOfFunds %></p></b>
<ul>
<% foreach (string genreName in
Model.FundsList) { %>
<li>
<%: genreName %>
</li>
<% } %>
</ul>
//OUTPUT :
//*************************************************************
// Function
to get list of funds and manipulate Funds
public ActionResult
getFundsList()
{
List<Fund>
fundlistnew;
fundlistnew = dc.getFundsListClass();
var movies = fundlistnew ;
return View(movies.ToList());
}
// HTML PART
<table>
<tr>
<th></th>
<th>
FundID
</th>
<th>
FundName
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Edit", "Edit",
new { id = item.FundID })%>
|
<%: Html.ActionLink("Details",
"../Home/getFundsbysearch/", new { id = item.FundID })%> |
<a href="javascript:void(0)" onclick="deletedata(<%:item.FundID %>)">Delete</a>
</td>
<td>
<%: item.FundID%>
</td>
<td>
<%: item.FundName %>
</td>
</tr>
<% } %>
<p>
<%: Html.ActionLink("Create New",
"CreateFunds")%>
</p>
</table>
<script type="text/javascript" >
function deletedata(id) {
if (window.confirm("ARe
you sure to delete")) {
window.location = "/Funds/Delete/"
+ id.toString();
}
}
</script>
//OUTPUT :
//*************************************************************
// Create New Fund
// Note that we created two functions to create new fund
// This function will load template to create new Fund
public ActionResult
CreateFunds()
{
return View();
}
//This function will post data with object Fund Class
[HttpPost]
public ActionResult
CreateFunds(Fund Fd)
{
int j = Fd.CreateFundsMethod();
if (j > 0)
{
return Redirect("getFundsList");
}
else
{
return View();
}
}
// HTML PART
<h3>Create New Funds </h3> <br /><br />
<% using
(Html.BeginForm()) { %>
<%: Html.ValidationSummary(true)
%>
<fieldset>
<legend>Fund</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.FundName) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.FundName) %>
<%: Html.ValidationMessageFor(model =>
model.FundName) %>
</div>
<p>
<input type="submit"
value="Create"
/>
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back
to List", "getfundslist")
%>
</div>
//OUTPUT :
//*************************************************************
public ActionResult
Edit(int? id)
{
if (id.HasValue)
{
int j = Convert.ToInt32(id);
ViewData.Model = dc.getFunddetailByFundID(j);
}
return View();
}
[HttpPost]
public ActionResult
Edit(Fund Fd)
{
int j = Fd.UpdateFunddetails();
if (j > 0)
{
return RedirectToAction("getFundsList");
}
else
{
return View();
}
}
public ActionResult
Delete(int id)
{
dc.FundID = Convert.ToInt32(id);
int j = dc.DeleteFund();
return RedirectToAction("getFundsList");
}
// HTML PART
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fund</legend>
<%: Html.HiddenFor(model => model.FundID ) %>
<div class="editor-label">
<%: Html.LabelFor(model => model.FundName) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.FundName) %>
<%: Html.ValidationMessageFor(model =>
model.FundName) %>
</div>
<p>
<input type="submit"
value="Save"
/>
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List",
"getfundslist") %>
</div>
}
}
//OUTPUT :
}
}