Tag Archives: HTML

MVC, Ajax, and jQuery

Screen Shot 2012-10-18 at 11.46.55 AMMany people see Ajax as the technology that saved the web, that made it possible to create much richer Web 2.0 applications than was ever possible using just HTML and plain old JavaScript. Part of the key to Ajax’s success is that it uses standards-based, widely implemented technologies instead of proprietary tools like Flash, Air, Silverlight, and many others that have sprung up to overcome the perceived limitations of HTML. Ajax has the benefit of ubiquity: all modern browsers have an implementation of JavaScript and
include the key object used to make asynchronous calls to the server, XmlHttpRequest.

Ajax is a powerful web technology because it makes pages far more interactive to the user, performing actions and updating parts of the page without requiring a full page refresh and accompanying flash of a blank page. This is one of the biggest visual differences between a web application and a rich client application, and gives the illusion of running on the client machine even though it is in a browser. An “Ajaxified” page feels faster to the user and reduces the load on the server by requesting small chunks of data and HTML rather than the content of full pages on every user action. Ajax is inherently asynchronous, so it leaves the user interface responsive to the user even if the last operation takes a while to complete.

Ajax is not, however, a panacea. It is a bit past its prime as the buzzword du jour of the last decade, but it is still too easy to get carried away with it and use it as though it solves all web problems. Here are a few of the problems:

  • Ajax requires that JavaScript be enabled on the client browser, not something you can assume in this day and age of security threats.
  • Unless you plan carefully to hook your pages into the browser’s history, the user won’t be able to use the back button to return to a previous page state. This is something that can be a bit unsettling to a user, when the back button takes them to an entirely different page rather than an earlier state of the same page.
  • By default, users also won’t be able to bookmark a link to the one product out of your entire catalog that they want to buy for their kid’s next birthday. This is because the application has to build in support for supporting page state through the URL.
  • Sites that make heavy use of JavaScript may come with many hundreds of thousands of bytes of script files. Even with caching, that can slow things down dramatically.
  • It also doesn’t help that JavaScript is notoriously slow, although modern browsers are improving performance.

Nevertheless, a well-designed site can handle most of these problems, both through careful design and judicious use of Ajax and other client-side features. The vast improvement to the user experience on sites that use Ajax can easily be worth the potential negatives, particularly since careful design can largely negate the problems.

In the purest sense, it may seem like nonsense to talk about MVC and Ajax together, since they occupy entirely different worlds within a web application. MVC is a server-side technology: the browser rendering pages doesn’t have a clue about models, views, and controllers. All that the browser sees is HTML and whatever the view embeds in the page it sends to the browser. Likewise, Ajax is a client-side technology that makes clever and sophisticated use of JavaScript and HTML’s document object model (DOM) to make pages far more interactive than is possible with just HTML. Of course, Ajax makes calls to the server to receive data used to update the page in response to user actions, but most of the time that is a clean, well-defined interface, often using some kind of web service implemented on the server. On the face of it, it doesn’t seem like there should be much to cover in a joint MVC/Ajax chapter, right?

Well, no, not right (as you probably guessed, based on the fact that this chapter exists). It turns out that there are some nice synergies in using the two technologies together. This is because MVC includes features that make it easier to implement custom Ajax features in a web page and because Ajax on the client can interact with action methods on the server to more effectively respond to user requests. This chapter will introduce you to these two broad ways that MVC can work together: on the server, mostly through features you can include in view definitions, and on the client in the client-side JavaScript you can include in a page. One nice thing about using these technologies together is that you can avoid writing much, if any, JavaScript code if you want, or you can write as much as you want to really make your pages come alive for users!

James Curtis

This post is an excerpt from the online courseware for our MVC 4.0: Validation and Working with Ajax written by expert James Curtis.

James Curtis  is a .NET Developer that primarily works in the UX space. He has worked on and for several large projects alongside Microsoft Consulting. James has spoken at several code camps about UX development for ASP.NET and SharePoint. He is an active participant in the development community tweeting and blogging about several topics in the UX area. James is an active consultant and is also assisting in several Start-ups contributing his UX experience.

HTML Helper Classes

HTML helpers are implemented in the System.Web.Mvc.HtmlHelper and HtmlHelper<T> classes. Views and partial views in MVC have an Html property that expose an HtmlHelper class, making it easy to use in a view. If you examine the interface of the HtmlHelper class in the documentation, you’ll find that it doesn’t implement most of the helper methods as native methods on the class. Instead, most of the helpers are extension methods implemented in the System.Web.Mvc.Html namespace, and HtmlHelper merely functions as
an anchor point for those helpers. Although HtmlHelper is most useful as the source of the helper extension methods, it has a number of its own native methods, of which Table 1 lists a few.

Method Description
AntiForgeryToken Adds a hidden form field with an anti-forgery token, used to
defend against cross-site request forgery (CSRF) attacks.
You can also extend this by passing in a salt value, domain
and path.
AttributeEncode HTML-encodes an attribute value.
EnableClientValidation Turns on client-side validation, causing the helpers to
generate the necessary client-side code.
Encode HTML-encodes a string or object value passed to the
method.
HttpMethodOverride Returns the value of a hidden field that identifies an override
method for the HTTP data-transfer method used by the
client.

Table 1. Some useful native methods of HtmlHelper.

The native HTML helpers included with HtmlHelper and its extension methods are useful, but cover only the most commonly used HTML elements. You’ll probably find yourself wanting more, and it is relatively easy to write your own helper methods, or even throw away the built-in helpers and use your own custom helper methods instead. Then, instead of referencing the System.Web.Mvc.Html namespace in your project, you replace it with your
namespace with your custom helper extension methods. This is just another way that you’re in control in MVC.

Types of HTML Helper Methods
MVC includes three broad classes of HTML helper methods: untyped helper methods, strongly-typed helper methods, and templated helpers. The untyped helper methods first appeared in the initial release of MVC, version 1, and generally take a string with the name of the property to which it is bound at runtime. The following code is an example of using a regular HTML helper to display a label, text box, and validation message to edit a Name property of the view model object, using the Label, TextBox, and ValidationMessage helper
methods.

A strongly-typed helper has “For” appended to the name of the method and takes a lambda expression that binds the helper to a model property at design time. This is in contrast to a regular helper that takes a string parameter. Strongly-typed helpers have the benefit of catching many kinds of problems at compile time instead of runtime, and IntelliSense fully supports them when you write code. The following code is an example of using strongly-typed helpers for the same Name property of the previous code, using the LabelFor,
TextBoxFor, EditorFor and ValidationMessageFor methods. Notice that each takes a lambda expression to bind the helper at design time.

@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.EditorFor(model => model.Notes) @Html.ValidationMessageFor(model => model.Notes)

Using a lambda expression lets you pass both the field that the helper is binding to and the value of the field. The strongly-typed helper method uses this information to intelligently determine how to display the data. It really is a rather elegant way to pass the information to the helper method.

TIP: Try misspelling a field name to see what happens. Specifically, misspell one
of the field names in one of the TextBox helper methods in the Edit view of
the AWLTProducts project, such as changing “Name” to “Nam.” You’ll find
that when you edit a product’s data you will receive a Compilation Error
since the Product model does not contain a definition for “Nam”.

Code that uses strongly-typed methods looks a bit more complex and requires more typing than the untyped versions, but only a little. And because the fields you are using are strongly typed, IntelliSense can help you where it couldn’t with just strings, as shown in Figure 12. Another benefit of using stronglytyped helper methods is that refactoring tools can update the views if you change field names.

figure12intellisenseFigure 12. IntelliSense provides a list of the properties of the Product object.

Templated helpers take the methods to an entirely different level, using built-in and custom templates to give you fine control over the HTML generated based on various templates. You can even throw an entire custom object at a templated helper, and the helper will use reflection to render all its properties—including nested properties—based on the templates defined for each data type, and reverting to a text box for any data types for which it has no template. The following code is an example of using a template helper to edit an entire view model, not just a single property of the object, using the EditorForModel method.

James Curtis

This post is an excerpt from the online courseware for our MVC4.0: Working with Data course written by expert James Curtis.

James Curtis  is a .NET Developer that primarily works in the UX space. He has worked on and for several large projects alongside Microsoft Consulting. James has spoken at several code camps about UX development for ASP.NET and SharePoint. He is an active participant in the development community tweeting and blogging about several topics in the UX area. James is an active consultant and is also assisting in several Start-ups contributing his UX experience.

The Magic of HTML

Thumbnail for 587

When people first began working with HTML, it seemed like magic. The fact that anyone could type a bunch of seemingly random directions and symbols into a computer, and suddenly shapes and images would appear, was something that some people could not fathom. As HTML, or hypertext markup language, evolved over the next few years, the power of the language grew. Fast-forward to today, and HTML is all around us. It is present, in some form, in every website we visit, every app we use, and every social media platform we update.

It is currently in its fifth iteration, and HTML5 is more powerful, robust, and flexible than any previous version of HTML. Knowing how to use it puts a powerful tool at your fingertips. An online HTML5 tutorial can help you learn the language quickly and easily, ensuring that you can put your new knowledge to use immediately. Combine your HTML5 tutorial with a C# video course, and not only will you be able to create an attractive website for your employer or your own small business, but you will also be able to network it, and set up intranet communications between everyone who may need access to it. HTML is not magic, but when used properly it can do almost magical things. Master it, and you will have a skill that many, many people will want.

XAML vs. HTML ain’t like VB vs. C#

windows-8-logo0817

 

Before Windows 8 apps came along, I spent a lot of time writing courseware for both VB and C#, and converting between the two was relatively easy–I got it down to a science. At worst, it involved some minor changes, once you got past the language differences. And those minor changes got smaller and smaller with each version of the languages.

So, wow, was I surprised to find that it’s nothing like that when comparing C# and JavaScript apps for Windows 8.

Basically, they have little, if anything, in common. Because C# (and VB) use the .NET Framework, more or less, and JavaScript apps use WinJS, the tools, classes, and even concepts are different. I was totally surprised how different the environments are, down to big differences in the available controls–things you find in JavaScript simply aren’t available to C#/VB developers. Want a date picker control? Better look outside Visual Studio to find that control (and several others that JavaScript supplies but C#/VB do not).

Anyway, my point is that if you’re a writer (or a developer) thinking that you can create apps in C# and then later convert them to JavaScript (or vice versa) think again. That ain’t happening.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Does your Help need Help?

Writing a ton of HTML code to support almost any kind of application, particularly one that maintains data, can be breathtakingly tedious. You’ll need to pepper the view with code nuggets, snippets of code embedded in the view to read from and write to the view’s model and perhaps ViewData. Although it is simpler and more efficient to write this kind of code in MVC and ASP.NET than it was in classic ASP, it is still tedious.

IntelliSense

It would be nice if Microsoft were to provide a middle ground, a feature that retains for the developer a high degree of control over the HTML, but lessens the tedium of writing reams of HTML code and makes intelligent decisions about the HTML to emit. A middle ground between the two extremes would be nice!

Fortunately, they did. (Bet you saw that coming!) The feature is called HTML helpers, or just helpers or helper methods. These are methods in the framework that emit markup for the most common HTML elements, and help create wellformed, valid markup.

In this article we’ll discuss the different types of HTML helper methods used in MVC.

Types of HTML Helper Methods

MVC includes three broad classes of HTML helper methods: untyped helper methods, strongly-typed helper methods, and templated helpers. The untyped helper methods first appeared in the initial release of MVC, version 1, and generally take a string with the name of the property to which it is bound at runtime. The following code is an example of using a regular HTML helper to display a label, text box, and validation message to edit a Name property of the view model object, using the Label, TextBox, and ValidationMessage helper methods.

A strongly-typed helper has “For” appended to the name of the method and takes a lambda expression that binds the helper to a model property at design time. This is in contrast to a regular helper that takes a string parameter. Strongly-typed helpers have the benefit of catching many kinds of problems at compile time instead of runtime, and IntelliSense fully supports them when you write code. The following code is an example of using strongly-typed
helpers for the same Name property of the previous code, using the LabelFor, TextBoxFor, and ValidationMessageFor methods. Notice that each takes a lambda expression to bind the helper at design time.

Using a lambda expression lets you pass both the field that the helper is binding to and the value of the field. The strongly-typed helper method uses this information to intelligently determine how to display the data. It really is a rather elegant way to pass the information to the helper method.

TIP: Try misspelling a field name to see what happens. Specifically, misspell one
of the field names in one of the TextBox helper methods in the Edit view of
the DogApp project, such as changing “Age” to “Ag.” You’ll find that when
you edit a dog’s data any existing age doesn’t appear, and when you save the
data it stores it as zero, no matter what you put in the text box.

Code that uses strongly-typed methods looks a bit more complex and requires more typing than the untyped versions, but only a little. And because the fields you are using are strongly typed, IntelliSense can help you where it couldn’t with just strings, as shown in Figure 1. Another benefit of using strongly-typed helper methods is that refactoring tools can update the views if you change field names.

Figure 1. IntelliSense provides a list of the properties of the Dog object.

Templated helpers take the methods to an entirely different level, using built-in and custom templates to give you fine control over the HTML generated based on various templates. You can even throw an entire custom object at a templated helper, and the helper will use reflection to render all its properties—including nested properties—based on the templates defined for each data type, and reverting to a text box for any data types for which it has no template. The following code is an example of using a template helper to edit an entire view model, not just a single property of the object, using the EditorForModel method.

For the most part, you’ll want to avoid using untyped helpers because they rely on string parameters and so tend to be error prone. Whenever you can, let MVC, Visual Studio, and the language compiler help you write good quality code!

Get more training on ASP.NET MVC 2 & 3!

ldn-bbluetry