Date post: | 02-Jan-2016 |
Category: |
Documents |
Upload: | griffith-hogan |
View: | 33 times |
Download: | 0 times |
ASP.NET MVC Part I
Ventsislav PopovDeveloper Evangelist at Microsoft
ventsypopov.
com
ventsypopov.
com
AgendaBeforehand – ASP.NET Web FormsWhat is MVCWhat is ASP.NET MVC?ModelsViewsControllersValidationRoutingUnit TestsView engines
2ventsypopov.
com
ASP.NET Web FormsRich controls and toolsPostbacksEvent driven web developmentViewstateLess control over the HTMLHard to testRapid development
3ventsypopov.
com
Model – View - Controller
6
Controller - responsible for handling all user input
Model - represents the logic of the application
View - the visual representation of the model
ventsypopov.
com
ASP.NET MVCMore control over HTMLNo Codebehind Separation of concerns Easy to testURL routingNo postbacks No ViewState
7ventsypopov.
com
ModelsThe model should contain all of the
application business logic, validation logic, and database access logic.
ASP.NET MVC is compatible with any data access technology (for example LINQ to SQL)
All .edmx files, .dbml files etc. are located in the Models folder.
8ventsypopov.
com
Custom View Models
9
When you combine properties to display on a View
namespace ContosoUniversity.ViewModels{ public class AssignedCourseData { public int CourseID { get; set; } public string Title { get; set; } public bool Assigned { get; set; } }}
ventsypopov.
com
What is Controller? It is a classDerives from the base
System.Web.Mvc.Controller classGenerates the response to the
browser request
11
public class HomeController : Controller{ public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(); }
public ActionResult About() { return View(); }}
ventsypopov.
com
Controller ActionsPublic method of the Controller
classCannot be overloadedCannot be a static methodReturns action result
12
public ActionResult About(){
return View();}
ventsypopov.
com
Action ResultsController action response to a
browser request Inherits from the base
ActionResult classDifferent results types
13
ventsypopov.
com
Action Results TypesViewResult EmptyResultRedirectResult JsonResult JavaScriptResultContentResult FileContentResult FileStreamResultFilePathResult
15
ventsypopov.
com
Controller base class methodsView
Redirect RedirectToAction RedirectToRoute Json JavaScriptResult Content File
16
ventsypopov.
com
ViewsMost of the Controller Actions
return viewsThe path to the view is inferred
from the name of the controller and the name of the controller action. \Views\ControllerName\
ControllerAction.aspxA view is a standard (X)HTML
document that can contain scripts.script delimiters <% and %> in the
views 17
ventsypopov.
com
Pass Data to a ViewWith ViewData:
ViewData["message"] = "Hello World!";
Strongly typed ViewData: ViewData.Model = OurModel;
With ViewBag:
ViewBag.Message = "Hello World!";
18
ventsypopov.
com
Post data to a controller Verb Attributes
The action method in the controller accepts the values posted from the view.
The view form fields must match the same names in the controller.
19
ventsypopov.
com
[HttpPost]public ActionResult Edit(Movie movie){
if (ModelState.IsValid){
db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index");
}return View(movie);
}
HTML HelpersMethods which typically return
string.Used to generate standard HTML
elements textboxes, dropdown lists, links etc. Example: Html.TextBox() method
Usage is optionalYou can create your own HTML
Helpers
21
ventsypopov.
com
ValidationTwo types of validation error
messages generated before the HTML form
fields are bound to a class generated after the form fields are
bound to the classModel StateValidation Helpers
Html.ValidationMessage() Html.ValidationSummary()
22
ventsypopov.
com
RoutingThe Routing module is responsible
for mapping incoming browser requests to particular MVC controller actions.
Two places to setup: Web.config file Global.asax file
24
ventsypopov.
com
Routing SetupWeb.config file
25
<system.web><httpModules>
…
<system.web><httpHandlers>…
<system.webServer> <modules> …
<system.webServer> <handlers> …
ventsypopov.
com
Routing SetupGlobal.asax file
26
public class MvcApplication : System.Web.HttpApplication{
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home",
action = "Index", id = "" } );
}
protected void Application_Start() { RegisterRoutes(RouteTable.Routes); }}
ventsypopov.
com
URL Example
http://www.mysite.com/Home/About/6
{controller} = Home {action} = About {id} = 6
27
ventsypopov.
com
ventsypopov.
com
Unit TestsUsed for the business logic (not
DAL or View logic).Test individual “unit”of codeMake the code safe to modifyMock Object framework
When you lack “real” objects Create mocks for the classes in the
application Test with mock objects
29
ventsypopov.
com
View EnginesHandles the rendering of the view
to UI (html/xml);Different view engines have
different syntaxASP.NET MVC 3 Pre-included View
Engines:Web FormsRazor
31
ventsypopov.
com
Things to rememberWhat MVC stands forHow ASP.NET MVC differs from
Web FormsWhere is routing configuredHow to validate business logicHow to use helpersUnit tests basicsChoice between “View Engines”
33
ventsypopov.
com
Useful siteshttp://www.asp.net/mvchttp://msdn.microsoft.com/en-us/library/dd394709.aspx
http://stackoverflow.com/http://jquery.com/
34
ventsypopov.
com