Unit 3 ASP.net Mvc Notes
Unit 3 ASP.net Mvc Notes
Controller
// MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
Controller
public class MusicStoreController : Controller
{
// GET: MusicStrore
public ActionResult Index()
{
return View();
} } }
Create ASP.NET Web Application (.NET Framework) ->
select Empty -> MVC check box and create project.
Controller
Demo
HomeController.cs
using System.Web.Mvc;
namespace WebApplication8.Controllers
{
public class HomeController : Controller
Controller {
public string Index()
Demo {
return "Hello";
}
using System.Web.Mvc;
namespace WebApplication8.Controllers
{
public class HomeController : Controller
Controller {
public string Index()
Demo {
return "Hello";
}
namespace WebApplication8.Controllers
{
public class EmployeeController : Controller
{
Demo }
profile = "EMP 1";
else if (id == 2)
{
profile = "EMP 2";
}
else
{
profile = "No profile";
}
return profile;
}
public string Address(int id, string division) {
return "id= " + id + "division= " + division;
}
}
}
EmployeeController
View Demo
Step 5
Open Index.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
View Demo content="width=device-width" />
<title>Index</title>
</head>
<body>
<div> <h1>Hi, Home Controller and Index
method </h1>
</div>
</body>
</html>
Step 6
In HomeController.cs
using System.Web.Mvc;
namespace ViewDemo.Controllers
{
public class HomeController : Controller
View Demo {
// GET: Home
public ActionResult Index()
{
return View();
}
public ViewResult AboutUs()
{
return View();
}
}
}
Step 6
Do same in EmployeeController.cs and run
View Demo
Points
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
View Demo </head>
<body>
<div> <h1>Hi, Home Controller and Index method </h1>
</div>
<div>
<a href="/Home/AboutUs">Home - AboutUs</a>
<a href="/Employee/Index">Employee - Index</a>
<a href="/Employee/AboutUs">Employee - AboutUs</a>
</div>
</body>
</html>
If the view file is not available, the controller will try to check all the possibilities and
throw this error.
View Demo
A model is a class that contains the business logic of the
application. It also used for accessing data from the
database.
The model class does not handle directly input from the
Model in MVC browser. It does not contain any HTML code as well.
Models are also refers as objects that are used to
implement conceptual logic for the application.
A controller interacts with the model, access the data,
perform the logic and pass that data to the view.
To add the model, just right click on the Model folder of the
project and then follow this sequence Model->Add->New
Item->Visual C#->Code->Class.
// Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
Model in MVC using System.Web;
public class Student {
namespace MVCDemo.Models
Model {
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
}
//StudentController.cs
using System.Web.Mvc;
namespace MVCDemo.Controllers
{
public class StudentsController : Controller
Controller {
// GET: Students
public ActionResult Index()
{
return View();
}
}
}
<div class="form-group">
@model MVCDemo.Models.Student @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-
md-2" })
@{ <div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-
ViewBag.Title = "Index";
control" } })
} @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
<h2>Index</h2> </div>
<div class="form-group">
@using (Html.BeginForm()) <div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
{ </div>
</div>
@Html.AntiForgeryToken()
</div>
}
<h4>Student</h4>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<hr />
<div class="form-group">
<div class="col-md-10">
</div>
</div>
Output
Razor is a standard markup syntax that allows us to embed
server code into the web pages.
It uses its own syntax and keywords to generate view.
If there is server code in the web page, server executes that
ASP.NET code first then send response to the browser. It allows us to
Razor View perform logical tasks in the view page.
We can create expressions, loops and variables in the view
page.
It has simplified syntax which is easy to learn and code. This
file extension is .cshtml.
Razor code blocks are enclosed in @{ ... }
Inline expressions (variables and functions) start with @
Code statements end with semicolon
Variables are declared with the var keyword
Strings are enclosed with quotation marks
C# code is case sensitive
Razor Syntax C# files have the extension .cshtml
Rules
@{var price=60;}
<html>
<body>
@if (price>50)
{
<p>The price is greater than 50.</p>
}
</body>
Compact: Razor syntax is compact, enabling you to
minimize the number of characters and keystrokes
required to write code.
Razor Easy to Learn: Razor syntax is easy to learn where you can
Characteristics use your familiar language C# or Visual Basic.
Intellisense: Razor syntax supports statement completion
within Visual Studio.
<h2>Index</h2>
<h2>@DateTime.Now.ToShortDateString()</h2>
Razor View @{
Demo var d = DateTime.Now.ToShortDateString();
var m = "Hello";
}
<h2> Date is: @d </h2>
<h3> @m</h3>
@if(DateTime.IsLeapYear(DateTime.Now.Year) )
{
@DateTime.Now.Year @:is a leap year.
}
else {
@DateTime.Now.Year @:is not a leap year.
}
Razor View
//
Demo @for (int i = 0; i < 5; i++) {
@i.ToString() <br />
}
//
<ul> @foreach (var x in Request.ServerVariables) {
<li>@x</li>} </ul>
@{
var totalMessage = "";
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
Layout View <title>@ViewBag.Title</title>
</head>
Demo <body>
<div>
@RenderBody()
</div>
</body>
</html>
_myLayoutPage.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
Layout View @Scripts.Render("~/bundles/modernizr")
</head>
Demo <body>
<div>
@RenderBody()
</div>
<footer class="panel-footer">
@RenderSection("footer", true)
</footer>
</body>
</html>
Layout View
Demo
@{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_myLayoutPage.cshtml";
}
<h2>Index</h2>
<div class="row">
Layout View <div class="col-md-4">
Demo <p>This is body.</p>
</div>
@section footer{
<p class="lead">
This is footer section.
</p>
}
</div>
A partial view is a reusable portion of a web page.
It is .cshtml or .vbhtml file that contains HTML code.
It can be used in one or more Views or Layout Views.
You can use the same partial view at multiple places
Partial View and eliminates the redundant code.
Partial View
_MenuBar.cshtml
Cut the layout code and paste in _MenuBar
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-
target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
Partial View @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new {
@class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
You can render the partial view in the parent view using
the HTML helper methods:
Rendering @html.Partial(),
@html.RenderPartial(), and
Partial View
@html.RenderAction().
@html.Partial()
The @Html.Partial() method renders the specified
partial view. It accepts partial view name as a string
parameter and returns MvcHtmlString. It returns an
HTML string, so you have a chance of modifying the
HTML before rendering.
Rendering Now, include _MenuBar partial view in _Layout.cshtml using
Partial View @html.Partial("_MenuBar")
@html.Partial()
Rendering
Partial View
@html.RenderPartial()
The @html.RenderPartial() method is the same as the
@html.Partial() method except that it writes the
resulted HTML of a specified partial view into an HTTP
response stream directly. So, you can modify it's HTML
before render.
The RenderPartial() method returns void, so a
Rendering semicolon is required at the end, and so it must be
enclosed within the @{ }.
Partial View
<body>
@{
Html.RenderPartial("_MenuBar");
}
@html.RenderAction()
The @html.RenderAction() method executes the
specified action method and renders the result. The
specified action method must be marked with the
[ChildActionOnly] attribute and return the
PartialViewResult using the PartialView() method.
To render a partial view using the RenderAction()
method, first create an HttpGet action method and
apply the ChildActionOnly attribute.
Rendering In Home controller add the below code:
Partial View
public class HomeController : Controller
{
[ChildActionOnly]
public ActionResult RenderMenu()
{
return PartialView("_MenuBar");
}
}
@html.RenderAction()
In Layout, include below code
<body>
Rendering @{
Html.RenderAction("RenderMenu", "Home");
Partial View }
The HtmlHelper class renders HTML controls in the
razor view.
It binds the model object to HTML controls to display the
value of model properties into those controls and also
HTML Helpers assigns the value of the controls to the model properties
while submitting a web form.
So always use the HtmlHelper class in razor view instead of
writing HTML tags manually.
HTML Helpers
@Html is an object of the HtmlHelper class. (@ symbol is
used to access server-side object in razor syntax).
Html is a property of the HtmlHelper class included in base
class of razor view WebViewPage.
The ActionLink() and DisplayNameFor() are extension
methods included in the HtmlHelper class.
Extension Method Strongly Typed Method Html Control
Html.ActionLink() NA <a></a>
Html.TextBox() Html.TextBoxFor() <input type="textbox">
Html.TextArea() Html.TextAreaFor() <input type="textarea">
Html.CheckBox() Html.CheckBoxFor() <input type="checkbox">
Html.RadioButton() Html.RadioButtonFor() <input type="radio">
Html.DropDownList() Html.DropDownListFor() <select>
<option>
</select>
HtmlHelper Html.ListBox() Html.ListBoxFor() multi-select list box: <select>
Methods Html.Hidden() Html.HiddenFor() <input type="hidden">
Html.Password() Html.PasswordFor() <input type="password">
Html.Display() Html.DisplayFor() HTML text: ""
Html.Label() Html.LabelFor() <label>
Html.Editor() Html.EditorFor() Generates Html controls based
on data type of specified
model property e.g. textbox
for string property, numeric
field for int, double or other
numeric type.
<input type="text" name="fname" id="fname" />
@Html.TextBox(“fname”, “RK KEYNOTES”)
@Html.TextBox("fn", "RAVI", new { style = "background-
color:Red; color:White; font-weight:bold", title="Enter
HTML Helper Name"})
Demo @Html.Label("firstname", "First Name")
@Html.Password("Password")
@Html.TextArea("Comments","",5,20,null)
@Html.Hidden("ID")
In CSS file:
.greenbox{
background-color:Red;
color:White;
HTML Helper font-weight:bold
Demo }
In VIEW file:
<link href="~/Content/Site.css" rel="stylesheet" />
@Html.TextBox("fname", "RK", new { @class = "greenbox"})
In ASP.NET MVC application, the controller defines
action methods that are used to handle user requests
and render view as the response. A controller can have
any number of actions.
MVC Actions RedirectResult Redirect It is used to redirect to another action method by using its URL.
JavaScriptResult JavaScript It is used to return a script that can be executed on the client.
EmptyResult (None) It represents a return value that is used if the action method
must return a null result.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
{
// GET: MusicStrore
Adding an public ActionResult Index()
{
Action method return View();
}
public string Welcome()
{
return "Hello, this is welcome action message";
}
}
}
To access the welcome action method, execute the application then access it by
using MusicStore/Welcome URL. It will produce the following output.
Action parameters are the variables that are used to retrieve user requested
values from the URL.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
public class MusicStoreController : Controller
Action Method {
Parameters // GET: MusicStrore
public ActionResult Index()
{
return View();
}
public string ShowMusic(string MusicTitle)
{
return "You selected " + MusicTitle + " Music";
}
}
} In URL, we have to pass the parameter value. So, we are doing it by this
URL localhost:port-no/MusicStore/ShowMusic?MusicTitle=Classic.
Action selectors are attributes that are applied on
action methods of a controller. It is used to select
correct action method to call as per the request. MVC
provides the following action selector attributes:
ActionVerbs
The MVC framework provides the filter attribute so that we
can filter the user requests. We can apply it to an individual
action or an entire controller.
ASP.NET MVC Filter is a custom class where you can write
custom logic to execute before or after an action method
ASP.NET executes.
MVC- Filters Filters can be applied to an action method or controller in a
declarative or programmatic way.
Declarative means by applying a filter attribute to an action
method or controller class and programmatic means by
implementing a corresponding interface.
Filter Type Description Built-in Filter Interface
Authorization Performs authentication [Authorize], IAuthorizationFilter
filters and authorizes before [RequireHttps]
executing an action
method.
Action filters Performs some operation IActionFilter
before and after an action
ASP.NET method executes.
OutputCache
Example
// MusicStoreController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
Authorize public class MusicStoreController : Controller
Example {
[Authorize]
public ActionResult Index()
{
return View();
}
}
}
Validation of user input is necessary task for the
application programmer. An application should allow
only valid user input so that we get only desired
MVC information.
Validation
ASP.NET MVC framework provides built-in annotations
that we can apply on Model properties. It validates
input and display appropriate message to the user.
Attribute Usage
Required Specifies that a property value is required.
StringLength Specifies the minimum and maximum length of characters that are
allowed in a string type property.
Range Specifies the numeric range constraints for the value of a property.
RegularExpres Specifies that a property value must match the specified regular
sion expression.
MVC CreditCard Specifies that a property value is a credit card number.
Validation CustomValidat
ion
Specifies a custom validation method that is used to validate a property.
DataAnnotation [Required]
Attributes public string StudentName { get; set; }
[Range(10, 20)]
public int Age { get; set; } }
//model
namespace mvcval6m.Models
{
Validation public class Class1
{
Demo public string username { get; set; }
}
}
//controller
using System.Web.Mvc;
namespace mvcval6m.Controllers
{
Validation public class HomeController : Controller
{
Demo // GET: Home
public ActionResult Index()
{
return View();
}
}
}
//view
@model mvcval6m.Models.Class1
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<head>
<script>
Validation
Demo function validate() {
if
(document.getElementById("txtuser").value.length == 0) {
document.getElementById("spuser").innerHTML =
"Name required";
return false;
}
}
</script>
</head>
<body>
<div>
@using (Html.BeginForm())
{
<table>
<tr><td>Enter
Name:</td><td>@Html.TextBoxFor(a => a.username, new
{id="txtuser" })</td><td><span id="spuser"></span></td></tr>
</div>
</body>
Output
In MVC, routing is a process of mapping the browser
request to the controller action and return response back.
Each MVC application has default routing for the default
HomeController. We can set custom routing for newly
Routing created controller.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action =
"Index", id = UrlParameter.Optional }
);
} } }
The URL pattern is considered only after the domain
name part in the URL. For example, the URL pattern
"{controller}/{action}/{id}" would look like
localhost:1234/{controller}/{action}/{id}.
Anything after "localhost:1234/" would be considered
as a controller name.
The same way, anything after the controller name
URL Pattern would be considered as action name and then the value
of id parameter.
URL Controller Action Id
http://localhost/home HomeController Index null