Advantages of ASP.NET MVC Framework
The ASP.NET MVC framework offers the following advantages:
It makes managing complexity easier by dividing an application into the model, view, and controller.
It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
It uses a Front Controller pattern that processes web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.
It provides better support for TDD.
It works well for web applications that are supported by large teams of developers and for web designers who need a high degree of control over the application behavior.
Example of using Javascriptresult in MVC
The JavaScriptResult is used to execute JavaScript code on the client sent from the server.
public ActionResult DoSomething() { script s = “$(‘#some-div’).html(‘Updated!’);”; return JavaScript(s); }
Call using
<%: Ajax.ActionLink(“click”, “DoSomething”, new AjaxOptions()) %> <div id=”some-div”></div>
ActionResult Types in ASP.NET MVC
EmptyResult
Represents a null or empty response It doesn’t do anything
ContentResult
Writes the specified content directly to the response as text
JsonResult
Serializes the objects it is given into JSON and writes the JSON to the response
RedirectResult
Redirects the user to the given URL
RedirectToRouteResult
Redirects the user to a URL specified via Routing parameters
ViewResult
Calls into a View engine to render a View to the response
PartialViewResult
This is similar to ViewResult, except it renders a partial View to the response, typically in response to an AJAX request
FileResult
Serves as the base class for a set of results that writes a binary response to the stream Useful for returning files to the user
FilePathResult
Derives from FileResult and writes a file to the response based on a file path
FileContentResult
Derives from FileResult and writes a byte array to the response
FileStreamResult
Derives from FileResult and writes a stream to the response
JavaScriptResult
Used to execute JavaScript code immediately on the client sent from the server
Passing multiple parameters to action in MVC
For example, suppose that you have an action method that calculates the distance between two points:
public void Distance(int x1, int y1, int x2, int y2) { double xSquared = Math.Pow(x2 - x1, 2); double ySquared = Math.Pow(y2 - y1, 2); Response.Write(Math.Sqrt(xSquared + ySquared)); }
Using only the default route, the request would need to look like this:
/simple/distance?x2=1&y2=2&x1=0&y1=0
We can improve on this by defining a route that allows you to specify the parameters in a cleaner format.
Add this code inside the RegisterRoutes methods within the Global.asax.cs.
routes.MapRoute(“distance”, “simple/distance/{x1},{y1}/{x2},{y2}”, new { Controller = “Simple”, action = “Distance” } );
We can now call it using /simple/distance/0,0/1,2
Passing parameters to actions in ASP.NET MVC
You can pass in parameters to an action method by name via the query string. You can also pass in parameters via the URL segments, discoverable by position as defined in your routes.
public class SimpleController : Controller { public void Goodbye(string name) { Response.Write(“Goodbye” + HttpUtility.HtmlEncode(name)); } }
Invoke using /simple/goodbye?name=World or /simple/goodbye/world
Example of a simple controller
All public methods of a class that derive from Controller become action methods, which are callable via an HTTP request. The Hello action is invoked by going to http://localhost:port/simple/hello
using System; using System.Web; using System.Web.Mvc; public class SimpleController : Controller { public void Hello() { Response.Write(“<h1>Hello World!</h1>”); } }
Example of using AuthorizeAttribute with roles in MVC
The admin Controller is restricted to members of the Admins and SuperAdmins roles.
[Authorize(Roles=”Admins, SuperAdmins”)] public class AdminController { //Only admins should see this. public ActionResult Index() { return View(); } //Only admins should see this. public ActionResult DeleteAllUsers() { //Thankfully, this is secured by the Authorize attribute. } }
How does the AuthorizeAttribute work in ASP.NET MVC
The AuthorizeAttribute is the default Authorization fi lter included with ASP.NET MVC. We can use it to restrict access to an action method. Applying this attribute to a Controller is shorthand for applying it to every action method.
When applying this attribute, we can specify a comma-delimited list of Roles or Users. If you specify a list of Roles, the user must be a member of at least one of those roles in order for the action method to execute. Likewise, if you specify a list of Users, the current user’s name must be in that list.
If we don’t specify any roles or users, then the current user must simply be authenticated in order to call the action method. This is an easy way to block unauthenticated users from a particular Controller action.
If a user attempts to access an action method with this attribute applied and fails the authorization check, the filter causes the server to return a “401 Unauthorized” HTTP status code.
In the case that forms authentication is enabled and a login URL is specified in the web.config, ASP.NET will handle this response code and redirect the user to the login page.
Four Action filters in ASP.NET MVC
Authorize: This filter is used to restrict access to a Controller or Controller action.
HandleError: This filter is used to specify an action that will handle an exception that is thrown from inside an action method.
OutputCache: This filter is used to provide output caching for action methods.
RequireHttps: This filter, newly included in ASP.NET MVC 2, prevents non-SSL (HTTP) requests.
Display HTML attributes with HTML.Textbox helper
To display HTML attributes,we should call an overload of the textbox helper that supplies an explicit value. If you want to use View data lookup in these cases, just pass in null to the TextBox helper.
<%: Html.TextBoxFor(m => m.Name, "w3mentor" , new {@class=”mycssclass”}) %>
Output:
<input class=”mycssclass” id=”Name” name=”Name” type=”text” value=”w3mentor” />
Display explicit value in text box using Html.TextBox helper in ASP.NET MVC
The TextBox helper allows us to supply an explicit value and avoid View data lookup.
<%: Html.TextBox(“Name”, “w3mentor”) %>
Produces:
<input id=”Name” name=”Name” type=”text” value=”w3mentor” />
Html.TextBox Helper in ASP.NET MVC
The TextBox helper renders an input tag with the type attribute set to text. It is the most commonly used to accept free-form input from a user.
Example:
<%: Html.TextBox(“name”) %>
Ouput:
<input id=”name” name=”name” type=”text” value=”“ />
Set the value in the controller:
public ActionResult Edit(int id) { var product = new Product {Name = “ASP.NET MVC”} ViewData[“Name”] = product.Name; return View(); }
Display in view:
<%: Html.TextBox(“Name”) %>
Output:
<input id=” Name” name=”Name” type=”text” value=”ASP.NET MVC” />
Difference between HttpUtility.HtmlEncode method and Html.Encode method
Html.Encode can accept an object where as HttpUtility.HtmlEncode method cannot accept an object. Also when an object is passed to Html.Encode, it is converted to a string using CultureInfo.CurrentCulture before being encoded.
Return a Model in the View method in ASP.NET MVC
In the Controller method, you can specify the Model via an overload of the View method whereby you pass in the Model.
public ActionResult List() { var products = new List<Product>(); for(int i = 0; i < 10; i++) { products.Add(new Product {ProductName = “Product “ + i}); } return View(products); }
This sets the value of the ViewData.Model property to the value passed into the View Method. To get a strongly typed view, we can use the following page directive
<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<IEnumerable<Product>>” %>
Strongly typed views in ASP.NET MVC
Suppose that you have a list of Product instances you wish to display in a View. One means of doing this is to simply add the products to the View Data dictionary and iterate them over the View.
public ActionResult List() { var products = new List<Product>(); for(int i = 0; i < 10; i++) { products.Add(new Product {ProductName = “Product “ + i}); } ViewData[“Products”] = products; return View(); }
View to display strongly typed data:
<ul> <% foreach(Product p in (ViewData[“Products”] as IEnumerable<Product>)) {%> <li><%: p.ProductName %></li> <% } %> </ul>
Specify a View in a completely different directory structure to be rendered
You can use the tilde syntax to provide the full path to the View like so:
public ActionResult Index() { ViewData[“Message”] = “Welcome to ASP.NET MVC!”; return View(“~/Some/Other/View.aspx”); }
How to make an action to render a different View in ASP.NET MVC
Suppose that you want the Index action to render a different View. You could supply a different View name like so:
public ActionResult Index() { ViewData[“Message”] = “Welcome to ASP.NET MVC!”; return View(“NotIndex”); }
Redirect action using Redirect Result in ASP.NET MVC
The RedirectToAction() method can be used to return a RedirectResult that redirects a user from one controller action to another.
using System.Web.Mvc; namespace MvcApplication1.Controllers { public class ProductsController : Controller { public ActionResult Index() { return View(); } public ActionResult Details(int id) { if (!id.HasValue) return RedirectToAction(“Index”); //return View(); } } }
We can redirect to another controller’s action by using the overloaded method as:
return RedirectToAction("Details", "Somecontrollername");
Explicitly return a view name other than default
The name of the view is specified explicitly in the example below. The ASP.NET MVC framework determines the name of the view from the name of the action if it is not mentioned.
using System.Web.Mvc; namespace MvcApplication1.Controllers { public class ProductsController : Controller { public ActionResult Details() { return View("ProductDetails); } } }
In this case, the action returns a view at the following location:
\Views\Products\ProductDetails.aspx
Return a View Result in ASP.NET MVC
A ViewResult is the most common ActionResult returned by a controller action. A ViewResult in ASP.NET MVC represents a view. ViewResult is returned when you want to return HTML to the browser.
Example:
using System.Web.Mvc; namespace MvcApplication1.Controllers { public class ProductsController : Controller { public ActionResult Index() { return View(); } } }
The view that will be returned is \Views\Products\Index.aspx
