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>




  MasterPageFile has to refer to the location of the master file
  asp:Content with ContentPlaceHolderID TitleContent is referenced as master page title
  asp:Content with ContentPlaceHolderID MainContent is referenced as master page 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";




and extend asp:Content element with ContentPlaceHolderID="MainContent" as below

<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 ViewBag

Assign the value in the controller

ViewBag.MyMessage="hello";


and read it in the view

@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 ContentControl
Add Views/Home/Index.aspx - embedded content
Add Controllers/HomeController.cs - controller for views under Views/Home
global.asax.cs - created by Visual Studio

More info and samples on: www.devarchweb.net

How to pass data between controller and View with model in ASP MVC 2

public class MyModel
{
  public string MyMessage { get; set; }
}




In the controller, create new instance of MyModel class, set the property and pass to the view


public ActionResult Index()
{
  var model = new MyModel();
  model.MyMessage = "hello model";
  return View(model);
}




You need to update the view:
1. tell the view page about the type of the model in the inherits section, "AspMvcDemo1.Models.MyModel"
2. use any model class property - intellisense works here, but if you make a typo, compiler will not catch it!


<%@ 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 handlers

public 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.
You can add another routing or modify 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>




RouteArea

- when 2 controllers maps to the same URL, the first one in .csproj file gets used
- when two actions in one method with the same argument name are used, they get precedence based on alphabetical order of type name (bool, int, string)

More info and samples on: www.devarchweb.net

How to use bundles BundleConfig.cs is created by Visaul Studio under App_Start folder

public 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"));
  }
}


Defined bundles can be rendered e.g. in Views/Shared/_Layout.cshtml

<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>



page details are in myview.cshtml that gets embedded into _layout.cshtml

@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>


CompanyName.cshtml

<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=1

string 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 button

public class LoginController : Controller
{
 public ActionResult Login(string userName, string password)
 {
  this.Response.Cookies.Add(new System.Web.HttpCookie("userName", userName));
 }
}


Read cookie when login page gets loaded

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 model

public 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);
}




You need to update the view to describe type that will hold the collection as List<"AspMvc2Empty.Models.Person">


<%@ 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>


or in MVC 4 with Razor syntax

@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 ListBox

public 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);
  }
}


Code in the view could look like below

@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" />
}


Note: when RadioButton is inside a container (div, td) then @: must be ommited

Wenn uses clicks "Login", the action called will the Index method in HomeController and
values from input elements will be passed as arguments.

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.
It can be achieved with FilePathResult, FileContentResult or FileStreamResult.

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
c:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\WebDev.WebServer40.EXE or WebDev.WebServer20.EXE based on .net you use.

This is a Dev server that is sometimes called as Cassini and it does not accept requests from remote machines.

In order to be able to debug request coming from remote machines, you can install
Fiddler and setup it as a proxy
on the machine where you have Visual Studio.
- In Fiddler, Tools > Fiddler Options, tab Connections, ensure that Allow remote clients to connect is set
- Close Fiddler
- Create a new HKEYCURRENTUSER\SOFTWARE\Microsoft\Fiddler2\ReverseProxyForPort of type DWORD and set the its decimal value to the port that you
see in Internet Explorer that was opened by Visual Studio when you started debugging (usually above 30000, e.g. ).
- Start Fiddler.
- Start debugging your application
- In a browser (local or remote machine), go to http://{computer name}:{port above 30000}/{SpecificPage}
- If you set a breakpoint inside a web service method in Visual Studio, Visual Studio will stop the request execution there




More info and samples on: www.devarchweb.net