This is my version of a Hello World application. I don’t want to just write “Hello World!” to the screen in a web page because, well, that’s just too basic. So what I’ll do is write a very simple form, post the form back to itself (the same page), collect data from the form, then display the data.
While extremely simple, this demonstrates a few different key functions of a web application – collecting and posting data, gathering that data, then doing something with the data. It also gives a simple demonstration of code logic mixed inline with HTML – a common practice when using Razor pages.
Like most of my code sample posts, I’m not specifically writing for efficiency, performance, or security here – just showing one (of many) way to accomplish something.
The below is the full text of a page I named HiThere.cshtml.
@{ string userName = Request.Form["userName"]; } <div> @if (!IsPost) { <form method="post"> What's your name? <input name="userName" type="text" /> <input type="submit" /> </form> } else { <div>hi @userName!</div> } </div>
Even though its simple, let’s break it down.
Lines 1-3 define a local variable of type string and assign it to whatever was posted to this page with a form input name of userName. If nothing was posted to the page then the variable of course will be null.
Line 5 checks to see if this is the first load of the page or if it was posted-to. If it was *not* posted-to (IsPost is a boolean check for a postback, ! means not) then I want the form to display and ask the user what their name is – and give them an opportunity to enter it and submit the form.
Line 10 is an extension of that check… if the form *was* posted-to, then don’t show the form and only show Hi <whatever>!.
That’s it! I said it was simple and it is! :)
Happy coding!