Archive for January, 2012

ASP.NET MVC – Hello with textbox and button

Posted in MVC on January 19, 2012 by Jon Spencer
I have started my new job, and am self-teaching ASP.NET and MVC. Prior experience has been all client/server apps, so doing stuff in the web world is a bit new. Same concepts, just implemented in a new way.
 
Since the best way to learn how to swim is to be thrown in a deep pool filed with sharks…I voluntered to create a dashboard to track transactions from our stores. While doing this, I thought I would first try a ‘Hello World’ project, but allow the user to enter his/her name in a text box, press submit, and then redirect to the index page with the new inputed name. Fairly simple ‘Hello’ application….or so I though! BTW, I am using VS 2008, ASP.NET 3.5, MVC 2, and coding in C#.
 
First, I created a new project. File-New Project-ASP.NET MVC 2 Web Application. I called my project ‘HelloName’ and went with the defaults from here.
 
I am doing all my work on the Index page, so I will need an initial value for the name variable, and also a way to change this variable and display the inputed name on the re-rendered Index.
 
First, the code for Index.aspx:
 
<% @PageLanguage=”C#”MasterPageFile=”~/Views/Shared/Site.Master”Inherits=”System.Web.Mvc.ViewPage” %> <asp:ContentID=”Content1″ContentPlaceHolderID=”TitleContent”runat=”server”> Home Page </asp:Content> <asp:ContentID=”Content2″ContentPlaceHolderID=”MainContent”runat=”server”>
<label>Your Name::</label>
<%using (Html.BeginForm()){ %>
     <%= Html.TextBox(“Name”)%><inputtype=”submit”value=”Submit Report Date”/>
<% } %>
<p><label>Hello, <%= Html.Encode(ViewData[“Name”])%>!</label></p>
</asp:Content>
 
The only stuff I added was the code between the <asp:Content>tag.  First, I create a basic label, then a form (since ASP.NET doesn’t implement forms, you need one for the textbox and button), a textbox which is named ‘Name’ and a submit button. For more info on why MVC doesn’t use forms, check out Building Web Apps without Web Forms by Chris Tavares.
 
Not a whole lot going on in the View.  The big question is how to get the property in the controller to bind to/from my textbox.  With code behind, it is fairy easy, since the HTML page can see the properties in your code.  But this causes the logic layer to be tightly coupled with the UI, the exact opposite of why we went with a MVC solution to begin with.
 
‘Bind’ these two together is not that difficult.  You notice we have a textbox that we named ‘Name’.  Now we will take a look and see how the controller is created to link all this up.

using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace HelloName.Controllers
{
     [
HandleError]
     publicclassHomeController : Controller
     {
          #region Properties
          privatestring _name;
          publicString Name
          {
               get { return _name; }
               set { _name = value; }
          }
          #endregion
     
          #region
ActionResults
          [
AcceptVerbs(HttpVerbs.Get)]
          publicActionResult Index()
          {
               if ((Name == null) || (Name == “”))
               {
                    Name =
“Nobody”;
               }
               ViewData[
“Name”] = Name;
               return View();
          }

          [AcceptVerbs(HttpVerbs.Post)]
          publicActionResult Index(string Name)
          {
               if ((Name == null) || (Name == “”))
               {
                    Name =
“Nobody”;
               }
               this.Name = Name;
               ViewData[
“Name”] = Name;
               return View();
          }
          #endregion
     }
}

In the above code, you can see there is a public property called ‘Name’.  This the where we will store the name inputed by the user.  However, on first load, we don’t have a name, so we handle setting this in the HTTP GET when the page is rendered by setting the Name to ‘Nobody’.  Next, the line ViewData[“Name”] = Name; will assign the Name property to the View Model.  It is this same naming convention that allows our View textbox to pull “Name” properly (in the view we used an Html.Textbox(“Name”) if you recall).
 
The hard part (for me at least) was how to essentially save the state (the user’s inputed) in a stateless environment.  This is handled in the HTTP POST.  You will notice we overwrote the ActionResult function for Index, adding a parameter called Name which is coming from the View Model (remember ViewData[“Name”]).  We now take the input data, check for null or an empty string, and then will assign the input to our controllers Name variable (this.Name).  The button click started the POST event, our action was handled by the Index page (taking in the argument passed), the value was set to our controller variable, then the page is rendered using the value in the controller variable to populate the textbox again, as well as the “Hello, <person>” label.
 
Not difficult, once you realize the name you set for the view data must be used in the view and also as the argument in the function that handles the POST.  This is what took me nearly half a day of experimenting with to get right.
 
Hope this helps you understand the GET, POST, and ViewData work that is going on when using MVC.  Enjoy!!!
Advertisements

How I became a Mad Computer Scientist

Posted in General with tags , on January 19, 2012 by Jon Spencer

“My father was a relentlessly self-improving boulangerie owner from Belgium with low grade narcolepsy and a penchant for buggery. My mother was a fifteen year old French prostitute named Chloe with webbed feet. My father would womanize, he would drink, he would make outrageous claims like he invented the question mark. Some times he would accuse chestnuts of being lazy, the sort of general malaise that only the genius possess and the insane lament. My childhood was typical, summers in Rangoon, luge lessons. In the spring we’d make meat helmets. When I was insolent I was placed in a burlap bag and beaten with reeds, pretty standard really.”

While I must admit I once held Dr. Evil in high regards, professionally and as a personal friend, his recanting and misrepresentation of my childhood as his own is egregious and in poor taste. On second though, that may very well be one of the core requirements for a Mad Scientist.

9 Real Life Mad Scientists

As most of you know, the science community is very cut throat, and even more so in the Mad Science community. Such underhanded tactics to gain notoriety are unfortunately not uncommon. Ahhh…how I long for the good ol’ days, when populariaty came from a simple show of galvanism, causing audiences to swoon, all with just with a few batteries and a couple of corpses. Giovanni Aldini , addio amico mio!

Regardless, it is not every profession that has the ability to hurl robots into the alien surface of Mars (“You Maniacs! You blew it up! Ah, damn you! God damn you all to hell!”), time travel (see prior comment), manipulate genome data to create a super-race(a much better plan that that of that bumbling oaf, Hugo Drax), or coding a virus to attack the PLC for a nuclear power plant! Through mad computer science, I have the ability to come closer in my dreams of ruling the world, much more so than any of my predecessors! Well, thats as long as the world remains reliant on computers. Luckily, over the summer I did some time travel, and am now working to avoid future events and that whole ‘mentat’ problem…which will bring me one step closer to WORLD DOMINATION!

BTW…my assistant says ‘Narf’!