Apr
2
2015

WebCamp MVC Events

imageI have been inspired to write some blog posts that feature highlights from a series of WebCamps I delivered along the west coast.  In this post, I am going to share a discovery I made when observing traditional ASP.NET (Web Form) developers attempt the switch to ASP.NET MVC.

The first question that might come to mind is: Why leave Web Forms?  The real answer is – you don’t have to.  However, here are a few reasons why many may choose to do so in the near future:

  • Web Forms are phat! …yet fat.  The page source is typically bloated with view state info.
  • Web Forms don’t encourage separation of concerns as does MVC.
  • Web Forms request/response model invokes many events and is process intensive.
  • Web Forms do not exist in ASP.NET 5.

The latter reason was the primary motivator for WebCamp attendees to consider moving to MVC because it exists prominently in ASP.NET 5 (by the way, Web Pages do too!)

You can learn a lot about what is on an attendee’s mind by a question he/she asked.  The following question is a classic example – and served as inspiration for this blog post and title:

“How do I respond to the click event of a button?”

The concept of interacting with elements on a page via event handlers is an easy concept to learn.  Unlearning it (for some) is a struggle.  MVC doesn’t use events like Web Forms do.  Instead of simply stating it doesn’t do that, I wanted to show how it was accomplished in MVC.  I used a very simple scenario -  one submit button on a page that displays a message when clicked.  Here is a snippet from the view:

<h2>Button Click Event in MVC</h2>
@using (Html.BeginForm())
{
    <input type="submit" name="submit" value="Submit" />    
}
<div>@ViewBag.Message</div>


And here is the code in the controller:


namespace
Palermo4Mvc.Controllers { public class DemoController : Controller { // GET: Demo public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(string submit) { ViewBag.Message = "Muhahaha!"; return View(); } } }
 

I went through the process of explaining how requests hit controllers first, then views were rendered.  Now that a simple task was accomplished, there was the inevitable questions that follow such as ‘What if I have two buttons?  How do I retrieve submitted values in the controller?  Do I still have access to querystring data? …’

What became clearer to me each time I presented a WebCamp is the need to bridge a gap starting with a simple process they already knew well.  Once the concept came into view (no pun) the attendees would organically accelerate their own learning path  Many new MVC developers have arisen from these events, and I was honored to be a part of that process!

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
blog comments powered by Disqus

Resources

Archives