Structure of master file
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
</head>
<body>
<h1>My MVC Application</h1>
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</body>
</html>
More info and samples on: www.devarchweb.net
Structure of view file<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
My Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
Hello
</asp:Content>
More info and samples on: www.devarchweb.net
Controller file content using System.Web.Mvc;
public class HomeController : Controller
{
public ActionResult Index()
{
return View(); // returned View will be ~/Home/Index.aspx
}
}
More info and samples on: www.devarchweb.net
How to pass data between controller and View in ASP MVC 2 ViewData["MyText"] = "from HomeController";
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
Hello <%: ViewData["MyText"]%>
</asp:Content>
More info and samples on: www.devarchweb.net
How to pass data between controller and View in ASP MVC 4 In MVC 4, you can use ViewBagViewBag.MyMessage="hello";
@ViewBag.MyMessage
More info and samples on: www.devarchweb.net
What are the basic files that need to be added to an empty app Add Views/Shared/Site.Master - xHTML site that hosts any site, e.g. Index.aspx as ContentControlMore info and samples on: www.devarchweb.net
How to pass data between controller and View with model in ASP MVC 2public class MyModel
{
public string MyMessage { get; set; }
}
public ActionResult Index()
{
var model = new MyModel();
model.MyMessage = "hello model";
return View(model);
}
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AspMvcDemo1.Models.MyModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
MyMessage: <%: Model.MyMessage %>
</asp:Content>
More info and samples on: www.devarchweb.net
How to pass data between controller and View with model in ASP MVC 4 MVC 4 approach in .cshtml@model AspMvcDemo1.Models.MyModel
...
MyMessage: @Model.MyMessage
More info and samples on: www.devarchweb.net
Describe application object with event handlerspublic class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start() { }
protected void Application_End() { }
// Application_BeginRequest
// Application_EndRequest
// Application_AuthenticateRequest
void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
...
Server.ClearError();
}
void Session_Start(object sender, EventArgs e) { }
void Session_End(object sender, EventArgs e) { }
}
More info and samples on: www.devarchweb.net
How to navigate between pages? <%: Html.ActionLink("TextVisibleToUser", "NameofMethodInController", "ControllerName", new { @myParamName = "abc" } )%>
More info and samples on: www.devarchweb.net
How to create a link that points out of project If you need to create a link that points out of the project where you cannot use @Html.ActionLink that requires controllers and views, you can use @Html.Raw @Html.Raw("<a href=\"" + Model.Link + "\">Go here</a>")
More info and samples on: www.devarchweb.net
Describe routing section for one page Routing is defined global.asax.cs. This file gets created by Visual Studio and it gets populated with default routing.public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default", // Route name - has to be unique
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // defaults if URL does not contain all sections, e.g. /Home will use /Home/Index
);
}
More info and samples on: www.devarchweb.net
Describe attribute routing options you need to call MapMvcAttributeRoutes()public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
// you can still use classic definition here
}
...
public class PersonsController : Controller
{
// /people will handled by PersonsController
[Route("people")]
public ActionResult View(string id) {...}
}
[RoutePrefix("people")] // prefix for all actions
[Route("{action=index}")] // default route
public class PersonsController : Controller
{
// /people/id
[Route("Id"), name="personById"] // named route
public PersonActionResult View(string id) {...}
}
..
// named route
<a href="@Url.RouteUrl("personById")">Person by id</a>
More info and samples on: www.devarchweb.net
How to use bundles BundleConfig.cs is created by Visaul Studio under App_Start folderpublic class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Site.css"
));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
}
}
<html>
<head>
...
@Styles.Render("~/Content/css")
</head>
<body>
...
@Scripts.Render("~/bundles/jquery")
</body>
</code>
More info and samples on: www.devarchweb.net
How to use sections web page Template is stored in shared/_layout.cshtml<html>
<body>
@RenderBody(); // includes view content that is not included in section(s)
@IsSectionDefined("mySection")
{
@RenderSection("mySection"); // includes specific section
}
else { ... }
@RenderSection("mySection", required:false); // skips if section does not exist
<body>
<html>
@section mySection {
a html content
}
More info and samples on: www.devarchweb.net
How to use partial pages<html>
<body>
@Html.Partial("CompanyName"); // includes HTML from myPartialView
<body>
<html>
<h1>Company One</h1>
@ ... another code
More info and samples on: www.devarchweb.net
How to read arguments passed through ?argName=argValue It is still possible to pass arguments to the controller like http://myserver/mysite?personId=1string myArgValue = Request.QueryString["personId"]; // myArgValue = 1
More info and samples on: www.devarchweb.net
How to read and write session variables In a controller code you can use Session, which is collection of values this.Session["userId"] = 123;
More info and samples on: www.devarchweb.net
How to write and read cookie (for userName) Write cookie inside the controller processing the request after user clicks the Login buttonpublic class LoginController : Controller
{
public ActionResult Login(string userName, string password)
{
this.Response.Cookies.Add(new System.Web.HttpCookie("userName", userName));
}
}
public class LoginController : Controller
{
public ActionResult Index()
{
HttpCookie cookie = this.Request.Cookies["userName"];
if (cookie != null)
{
ViewBag.UserName = cookie.Value;
}
else
{
ViewBag.UserName = string.Empty;
}
}
}
More info and samples on: www.devarchweb.net
How to authenticate users IIS: Windows Authentication must be enabled, Anynomous MUST be disabled
<system.web>
<authentication mode="Windows" />
</system.web>
// inside controller (or view)
string userName = this.Request.LogonUserIdentity.Name;
// alternatively you can use shortcut
string userName = this.User.Identity.Name;
More info and samples on: www.devarchweb.net
How to display collection with modelpublic ActionResult Index()
{
List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Paul", Height=178 });
people.Add(new Person() { Name = "George", Height=182 });
return View(people);
}
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<AspMvc2Empty.Models.Person>>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<table>
<% foreach (var item in Model) {%>
<tr>
<td> <%: item.Name %> </td>
<td> <%: item.Height %> </td>
</tr>
<% } %>
</table>
</asp:Content>
@model List<AspMvcBasics.Models.Person>
@{
ViewBag.Title = "People";
}
<table>
@foreach (var item in Model)
{
<tr>
<td>
@item.Name
</td>
<td>
@item.Height
</td>
</tr>
}
</table>
More info and samples on: www.devarchweb.net
Create Login form If the form contain a ListBox, it necessary to pass data to feed the ListBoxpublic class LoginController : Controller
{
public ActionResult PrepareLogin()
{
// data for list box
SelectList selection = new SelectList(
new[] {
new { Value = "A", Text = "Team A" },
new { Value = "B", Text = "Team B" },
new { Value = "C", Text = "Team C" },
},
"Value",
"Text"
);
return View(selection);
}
}
@model SelectList
@using (Html.BeginForm("HandleLogin", "Login"))
{
User name: @Html.TextBox("userName", "JohnFirst")
Password: @Html.Password("password")
Remember me: @Html.CheckBox("rememberUserName", false)
@Html.RadioButton("server", "s1", true) @:Server 1
@Html.RadioButton("server", "s2", false ) @:Server 2
@Html.ListBox("team", Model, new { size = 20 } )
<input type="submit" value="Login" />
}
public class LoginController : Controller
{
public ActionResult HandleLogin(string userName, string password,
string rememberUserName, string server, string team)
{
....
return View();
}
}
More info and samples on: www.devarchweb.net
Asscociate style with a textbox in a form@Html.TextBox("userName", (string)ViewBag.UserName, new { @class = "k-textbox" } )
More info and samples on: www.devarchweb.net
Display PDF file content, e.g. PDF In order to display content of file like PDF it necessary that an Action returns content of the file.public FilePathResult Report()
{
return new FilePathResult(@"c:\myfolder\myfile.pdf", "application/pdf");
}
// The FileContentResult approach enables file deletion in case the file was generated
public FileContentResult Report()
{
byte[] content = System.IO.File.ReadAllBytes(@"c:\myfolder\myfile.pdf");
System.IO.File.Delete(@"c:\myfolder\myfile.pdf");
return new FileContentResult(content, "application/pdf");
}
More info and samples on: www.devarchweb.net
Debugging remote requests When you start debugging an ASP MVC application, Visual Studio starts