250 likes | 421 Views
Working with MVC Preview Release. Sarang S. Datye Consultant – Microsoft Global Services India. Agenda. WebForms PageController Vs. MVC ASP.NET MVC Tenets Controller Conventions Single Action URL Model Binders Helper Methods for mapping
E N D
Working with MVC Preview Release Sarang S. Datye Consultant – Microsoft Global Services India.
Agenda • WebForms • PageController Vs. MVC • ASP.NET MVC • Tenets • Controller Conventions • Single Action URL • Model Binders • Helper Methods for mapping • Improved support for handling Input and Validation
WebForms ASPX Page Master Page User/Custom/Server Controls User/Custom/Server Controls Model
Page Controller ASP.NET Request ASPX Page Response
MVC Controller Model View
ASP.NET MVC ASPX Page Master Page User/Custom/Server Controls User/Custom/Server Controls Controller Model
ASP.NET MVC Tenets • Alternative • Testable • Extensible • Routable
ASP.NET MVC still has… • Web designer • Master pages • User controls • Membership/Roles/Profile • Globalization • Caching • HTTP intrinsics: • HttpContext • HttpRequest • HttpResponse • Etc.
Controller Conventions • Controller (now inherits from ControllerBase) • Must… • Be suffixed with “Controller” • Implement IController (or inherit from Controller) • Action • Must… • Be Public • Return ActionResult or void • Can’t… • Be generic • Have a NonActionAttribute • Have out/ref parameters
A Simple form post Scenario <form action="/Products/Create" method="post"> <table> <tr> <td>Product Name:</td> <td> <input id="ProductName" name="ProductName" type="text" value="" /> </td> </tr> <tr> <td>Unit Price:</td> <td> <input id="UnitPrice" name="UnitPrice" type="text" value="" /> </td> </tr> <tr> <td>Reorder Order:</td> <td> <input id="ReorderLevel" name="ReorderLevel" type="text" value="" /> </td> </tr> <tr> <td>Discontinued:</td> <td> <input id="Discontinued" name="Discontinued" type="checkbox" value="true" /> <input name="Discontinued" type="hidden" value="false" /> </td> </tr> <tr> <td></td> <td> <input type="submit" value="Save" /> </td> </tr> </table> </form>
Improvements in Preview 5… • The ability to publish a single action URL and dispatch it differently depending on the HTTP Verb • Model Binders that allow rich parameter objects to be constructed from form input values and passed to action methods • Helper methodsthat enable incoming form input values to be mapped to existing model object instances within action methods • Improved support for handling input and validation errors(for example: automatically highlighting bad fields and preserving end-user entered form values when the form is redisplayed to the user)
[AcceptVerbs] and [ActionName] • Separate Create and Save methods make code easier to read. • This can be problematic when it comes to redisplaying the same HTML form (e.g. in case of an error) • /Products/Create (This is where we start) • /Products/Save (This is where we post to) • Workaround • Create a single URL • Have a If/Else logic to identify GET/POST requests
Model Binders …in Preview 4 Difficult to read. The logic to create new product and assign values is repeated for similar implementations. DON’T REPEAT YOURSELF!
Model Binders… In Preview 5 [AcceptVerbs("POST")] public object Create(Product product) { // redisplay form immediately if there are input format errors if (!ViewData.ModelState.IsValid) return View(product); try { northwind.Products.InsertOnSubmit(product); northwind.SubmitChanges(); return RedirectToAction("Browse"); } catch (Exception error) { ViewData["Message"] = "Oops: Error"; UpdateModelStateWithViolations(product, ViewData.ModelState); return View(product); } }
Registering Model Binders • Approach 1: Param attribute on the Action method • Approach 2: ModelBinder attribute on the Type
Register Model Binders Continued • Approach 3a – Register binder at Application Start-up • Approach 3b – Register default binder (fallback)
UpdateModel and TryUpdateModel [AcceptVerbs("POST")] public object Edit(int id, FormCollection form) { var product = northwind.Products.Single(p => p.ProductID == id); try { UpdateModel(product, new[] { "ProductName", "UnitPrice", "Discontinued", "ReorderLevel" }); northwind.SubmitChanges(); TempData["Message"] = "Product Updated!"; return RedirectToAction("Edit", new { id = product.ProductID }); } catch (Exception error) { TempData["Message"] = "Oops - problems"; UpdateModelStateWithViolations(product, ViewData.ModelState); return View(product); } }
RedirectToAction • Submit and Save successfully • Hit the refresh…we get the below warning: Post/Redirect/Get Pattern http://en.wikipedia.org/wiki/Post/Redirect/Get
Handling Errors • Helper methods check ModelState • Helper methods automatically apply styling to the elements • Html.TextBox() helper method BEFORE: <tr> <td>Unit Price:</td> <td> <input id="UnitPrice" name="UnitPrice" type="text" value="" /> </td> </tr> AFTER: <tr> <td>Unit Price:</td> <td> <input class="input-validation-error" id="UnitPrice" name="UnitPrice" type="text" value="sdsds" /> <span class="field-validation-error">*</span> </td> </tr>
Summary • WebForms • PageController Vs. MVC • ASP.NET MVC • Tenets • Controller Conventions • Single Action URL • Model Binders • Helper Methods for mapping • Improved support for handling Input and Validation
Feedback / QnA • Your Feedback is Important! Please take a few moments to fill out our online feedback form at: << Feedback URL – Ask your organizer for this in advance>> For detailed feedback, use the form at http://www.connectwithlife.co.in/vtd/helpdesk.aspx Or email us at vtd@microsoft.com • Use the Question Manager on LiveMeeting to ask your questions now!
Contact (optional slide) • Blog Address www.dotnetbetaworks.com • Email Address sarang.datye@microsoft.com