Subscribe: mike's web log
Added By: Feedage Forager Feedage Grade B rated
Language: English
code  form  helper  input  markup  net web  net  option  page  pages  request  site  validation  web pages  web  webmatrix 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: mike's web log

mike's web log

mike pope's Web log

Published: Fri, 21 Oct 2016 00:00:00 GMT

Last Build Date: Fri, 21 Oct 2016 22:55:02 GMT


Paging and posting with the Razor WebGrid Helper

Wed, 06 Jun 2012 08:56:19 GMT

The ASP.NET Web Pages/Razor WebGrid helper lets you enable paging just by setting the rowsPerPage property:
var grid = new WebGrid(source: selectedData, rowsPerPage: 3);

Sometimes you want to be able to both to page and to filter the items that are displayed by the WebGrid helper. Here’s an example from the tutorial I posted on the site a couple of weeks ago:


The typical (?) approach here is to create a
element and set its method attribute to post:


(Leave blank to list all movies.)

In the page’s code, you create an is(IsPost) block in which you set up a parameterized SQL query and run that:
var db = Database.Open("WebPagesMovies") ;
var selectCommand = "SELECT * FROM Movies";
var searchTerm = "";

if(IsPost && !Request.QueryString["searchGenre"].IsEmpty() ) {
selectCommand = "SELECT * FROM Movies WHERE Genre = @0";
searchTerm = Request.QueryString["searchGenre"];

var selectedData = db.Query(selectCommand, searchTerm);
var grid = new WebGrid(source: selectedData, rowsPerPage:3);


Login redirection (and back) in ASP.NET Web Pages Razor

Tue, 08 May 2012 23:20:34 GMT

When you use membership security in ASP.NET Web Pages Razor, you can limit access to pages so that only logged-in users can see those pages. One way to do that, as explained before, is to add a test like the following to the top of a page (or to the _PageStart.cshtml page in the protected folder):

if (!WebSecurity.IsAuthenticated) {
If the user isn't logged in, they're redirected to the Login page (in this case, in the site's root).

Nice, but then the user still has to find their way back to the page they originally wanted. Ideally, after the user has logged in, you send them back to the original page automatically. And because they're now logged in, the gatekeeper code lets them through.

The usual way to approach this is to include a return URL address when you redirect to the login page. You can add it as a query-string value to the login URL. Then in the login page, once the user has logged in ok, you can get that return URL and jump back.

Here's an updated version of the code from above with some logic to create a return URL:

if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/Login?returnUrl=" + Request.Url.LocalPath);
For a URL like the following:


The Request.Url.LocalPath property returns this:


So the URL of the redirect to the Login page looks like this:


The login page can then return to the original page using logic like this:

var username = Request.Form["username"];
var password = Request.Form["password"];

Razor tip: Escaping the "@" character

Wed, 25 Apr 2012 17:20:43 GMT

In ASP.NET Web Pages/Razor, you use the @ character inside markup to mean "here be code." Like this:


But suppose you want to display the @ character instead of use it to mark code? Like this:

You use the @ character to mark inline code.

Try that in a .cshtml page and you're rewarded with a YSOD:

(Click to embiggen)

Simple fix: escape the @ character with ... another @ character. Like this:

You use the @@ character to mark inline code.

This makes the parser happy.

(h/t, as usual with parser questions: Andrew Nurse)

"Page" vs "PageData" objects in ASP.NET Web Pages

Thu, 19 Apr 2012 01:04:11 GMT

I was playing around with layout pages in ASP.NET Web Pages the other day and realized that there are actually two ways to pass data from the content page to the layout page: the Page object and the PageData object. You can do either of these in the content page:
Page.Title = "My Page";

PageData["Title"] = "My Page";
And then use either of these in the layout page:

So what's the difference? Here's what I got from my usual sources.

First, they really are the same object, just with differences in accessors. To show this, you could do the following:
Page.Me = "Mike";
and then get that value doing this:


Notice that the property/value names — Me, "me" — aren't even case sensitive.

Page is a dynamic object, meaning that the properties aren't fixed. You can make up your own properties for the object, like Page.Title, Page.MyValue, or Page.MyDogIsADoofus, and assign values to them.

Some folks consider syntax like Page.Title to be cleaner than using something like PageData["Title"]. However, this isn't really the same as normal property syntax (e.g., Request.Forms), because the dynamic property isn't getting compile-time type checking. And when you're using a dynamic property, some operations that look like they should work don't, like this:
Page.MyCount = "3";
// Fail with compiler error.

PageData["name"] [more]

Two small ASP.NET Web Pages (Razor) syntax tips

Wed, 11 Apr 2012 07:15:32 GMT

Two tips for Razor syntax: using a conditional attribute to set the selected attribute in a list item; working around a syntax restriction on x@x (e.g. ).

Tip 1
When I wrote recently about conditional attributes in ASP.NET Web Pages version 2 (new for that version), the example was the checked attribute of a checkbox. What about dynamically selecting an item in a list to remember the user’s choice after the page had been submitted. In an element, you can do this by setting the value attribute to the appropriate item in the Request collection:

In my case, I'm populating the
@foreach(var row in db.Query("Select DISTINCT Genre FROM Movies ORDER BY Genre")){

As each row is processed, I compare its Genre property/field against whatever was selected for the last page submission. If there's a match, the comparison returns true and the selected attribute is rendered.


Whitepaper on ASP.NET 4 security extensibility

Tue, 27 Mar 2012 15:17:22 GMT

Just a note that we just posted a whitepaper [PDF] written by the super-smart Stefan Schakow that discusses various ways in which ASP.NET 4 lets you extend security. For example, the paper describes:
  • How to specify various encryption algorithms for the section, including a custom class. (IOW, you can specify custom encryption for cookies, viewstate, etc.) There's now an API to manage custom encryption programmatically as well.

  • How to share forms authentication tickets between ASP.NET 2.0 and ASP.NET 4.

  • How to customize the security checks that are performed on incoming URLs. The security checks have been made pluggable so that you can use custom code for tasks like checking the length of the URL, checking for invalid or dangerous characters in the URL (for example, you can allows some characters that would be rejected by default), and matching portions of the URL to physical paths.

  • How request validation has changed for ASP.NET 4 and how to create a custom request-validation check.

  • How to use custom classes to encode HTML markup, headers, and URLs.

Full list of new features for ASP.NET Web Pages v2 Beta

Wed, 14 Mar 2012 22:52:04 GMT

Ok, we've now got a list of the new features for ASP.NET Web Pages v2 posted. Here's a list of the stuff that's been added since the December 2011 preview, as recounted in the updated Top Features doc:
  • Conditional attributes. Described earlier.

  • Validation.GetHtml has been changed to Validation.For. This method renders the goo that's used to hook client-side validation. See earlier.

  • The ~ operator is now recognized in HTML markup, so you don't need to use Href any more to resolve it. See earlier. I think this is my favorite feature, actually, even tho some might consider it comparatively small, dunno.

  • The Scripts helper was renamed to Assets (aka the Assets Manager), and the method names were tweaked. If you were using Scripts to register scripts or .css files, you have to change those references.
The rest of the doc describes the features that are new in v2 generally, starting in the December preview. If you installed that preview, then you'll know all about those. :-)

New for ASP.NET Web Pages: Better ~ operator support

Wed, 07 Mar 2012 08:40:38 GMT

Another improvement in the Beta release of ASP.NET Web Pages v2 is better integration of the ~ operator. The ~ operator, as ASP.NET people know, resolves to the root path of the current website. (See also) This is handy for creating URL paths, because it means that a) you don't need to hard-code an absolute URL and b) it isn't relative to the location of the current page. You don't need to worry about how many folders up you need to count (e.g. ../../path) or about what happens if the current page moves.

In Web Pages v1 (as in all ASP.NET code), the ~ operator is supported. But it only works in server code; it's not supported in native HTML, so to speak. If you want to create a path that uses the ~ operator, you therefore have to wrap the path into something that tells ASP.NET that you've got server code. Inside of markup, we use the Href method. For example, to create an link that incorporates it, you have to do this:


It works, but it's not very intuitive.

For v2 Beta, the .cshtml parser was enhanced so that it can recognize the ~ operator inline with normal markup. So the previous example can now be written like this:


No need for the Href method any more. In .cshtml pages (not plain .html or .htm pages, of course), you really can treat the ~ [more]

New for ASP.NET Web Pages: Conditional attributes

Thu, 01 Mar 2012 14:07:57 GMT

The beta release of ASP.NET Web Pages has been released (for example, as part of the ASP.NET MVC 4 Beta release). There are only a few differences from the December 2011 Developer Preview release. (Details when we've got them posted.)

A very cool feature is what's being called conditional attributes. The idea is that in markup, you can set the value of an element's attribute to a variable or expression. If the variable or expression returns false or null, the entire attribute is not rendered. There are a variety of uses for this, but it does a great job of solving a problem we inherited from HTML 1.0 (I think it was).

The problem manifests in cases where the simple appearance of an attribute name — regardless of its value — is sufficient to trigger HTML behavior. One case is the checkbox, i.e., the element:

Notice that in the first one, the checked attribute doesn't even have a value. Nonetheless, all of these work the same, namely they produce checkbox that's selected.

There's a similar situation with items in a selection list:

Technically, to select item B, the tag should read , but just including the selected attribute works.


Updated validation in Web Pages v2, Part 3

Sat, 25 Feb 2012 21:41:05 GMT

As noted previously, to display validation errors in ASP.NET Web Pages v2, you can use Html.ValidationMessage and Html.ValidationSummary. You can use one or the other or both. If you use both, one idea is to use ValidationMessage to show an "error icon" and ValidationSummary to show the details:

Rather a plain display. However, you can style the output of the messages using some reserved CSS class names, to wit:
  • input-validation-error
  • field-validation-error
  • validation-summary-errors
  • field-validation-valid
  • input-validation-valid
  • validation-summary-valid
For example, to make a particularly forceful (if ugly) error display, define classes like this:

And when the errors appear, they will be noticeable:


Formatting Client-Side Validation Errors


Updated validation in Web Pages v2, Part 2

Wed, 15 Feb 2012 08:55:34 GMT

In the last post, I laid out the basics of the Validation helper that's introduced in ASP.NET Web Pages v2. As I noted then, the helper supports both server- and client-side validation. Here's how to implement the client side.

So, you've got a page that already does this:
  1. In code, calls Validation.RequireField, Validation.RequireFields, or Validation.Add to register each input element for validation.

  2. In code, calls Validation.IsValid to determine whether all validation checks have passed.

  3. In markup, calls Html.ValidationMessage (for each validated element) and/or Html.ValidationSummary (once) to display any validation errors.
To add client functionality, you additionally do this:
  1. Register the following JavaScript libraries in the page:

    Two of the three libraries are loadable from a content delivery network (CDN), so you don't necessarily have to have them on your computer or server. However, you do have to have a local copy of jquery.validate.unobtrusive. For now, the easiest (if somewhat hacky) way to get this is to create a new Web Pages site based on one of the site templates (e.g. Starter Site). The site created by the template includes the jquery.validate.unobtrusive file in its Scripts folder, from which you can copy it to your site.

  2. In markup, for each element that you're validating, add a call to Validation.GetHtml(field) [more]

Updated validation in Web Pages v2

Wed, 08 Feb 2012 20:45:45 GMT

In v1 of ASP.NET Web Pages, you could add user-input validation by doing something like this in code:

if (name.IsEmpty()) {
    ModelState.AddError("Name", "You must enter a name.");

In v2, there's a new Validation helper that has some nifty features:
  • Methods to check for required fields, data types, string length, numeric ranges, the same values in two fields (as for new passwords), and patterns (i.e., RegEx).
  • Methods to display both field-specific and summary validation error messages.
  • Both client-side (instant) and server-side (post-submit) validation. "A double dose of valid!" (#)
For client validation, you also get:
  • Unobtrusive JavaScript techniques to minimize client code in the file, relying instead on semantic attributes in the markup.
  • No submit until all values are valid.

You can use the Validation helper to provide only server-side validation or both client- and server-side checks. (You always get server validation, for security reasons.) The basic steps for server-side validation are:
  1. Determine which input elements (fields) you want to validate

    You typically validate values in elements in a form. However, it is a good practice to validate all input, even input that comes from a constrained element like a