Using manually the ASP.NET MVC’s client side validation infrastructure

Using manually the ASP.NET MVC’s client side validation infrastructure

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. ASP.NET MVC client side validation is based on the jQuery validation plugin. It can be said that MVC’s client-side validation is an opinionated version of how jQuery validation should work in an ASP.NET MVC project. Despite this, the underlying implementation is fully based on jQuery’s. In this blog post I’ll show you how you can take advantage of this.

mvc

ASP.NET MVC Client Side validation requirements

First, here’s the list of things you need to do to enable client-side validation in an ASP.NET MVC project Make sure your client side code is loading both:

  • jquery.validate.js
  • jquery.validate.unobtrusive.js

Make sure your web.config has the following keys in appSettings with the follwoing values:

These settings can be overridden in a controller, make sure that is not happening. For example this would turn off client side validation if executed inside a controller’s action:

The next requirement is that you use attributes from System.ComponentModel.DataAnnotations in the Model class that is used in view where you want client-side validation enabled.

For example, if we want the Email field to be a valid email, and make the password and email fields required we would create a model like this:

Finally, we have to use the HtmlHelpers that generate the correct markup for all of this to work, and they have to be inside a form, for example

Getting away with using Client Side validation without a model

The last two requirements are actually optional. It is possible to take advantage of client side validation without having to create a model class and annotate it, which can be useful if you only use a couple of parameters (such as in the Login example).

If you inspect the markup that the helpers generate you’ll see that it’s actually pretty simple:

It turns out that to enable client side validation without using the HtmlHelpers and a model you just have to add an input with data-val="true" and then data-val- followed by validation method that you want to apply (e.g. data-val-required), the value of which will be the error message presented to the user (e.g. data-val-required="This is the error message"). This works because the MVC’s “unobtrusive validation” works by looking for inputs that are annotated with data-val attributes.

The data-valmsg-for‘s value is the name (not the id) of the input it refers to, and data-valmsg-replace="true" just means that the default message should be replaced, for example you could have a default message for the email field:

This message would then be replaced by any validation error that occurs in the email field, for example “The email is required”. If data-valmsg-replace="false" then the original message will never be replaced. The only consequence of an error is that the span’s class is changed from field-validation-valid to field-validation-error (this happens irrespectively of the value of data-valmsg-replace="false").

Some validation methods have parameters, for example RegularExpression. The way these work is very similar, they just need additional data-val- for their parameters. If you want to validate a text field using a regular expression for 5 to 8 digits, it would look like this:

If you create the markup yourself you can get away without having to create a model for your view. Using the login example from above, your controller action for handling the user logging in could simply be:

You’d have to make any server-side checks on the parameters yourself though.

Here is the list of the System.ComponentModel.DataAnnotation attributes you can use, and their data-val counterparts:

  • Compare
    • data-val-equalto="Error message"
    • data-val-equalto-other="The name of the other field"
  • CreditCard
    • data-val-creditcard="Error message"
  • EmailAddress
    • data-val-email="Error message"
  • MaxLength
    • data-val-maxlength="Error message"
    • data-val-maxlength-max="Maximum length (e.g. 5)"
  • MinLength
    • data-val-minlength="Error message"
    • data-val-minlength-min="Minimum length (e.g. 2)"
  • Range
    • data-val-range="Error message"
    • data-val-range-max="Max value"
    • data-val-range-min="Min value"
  • RegularExpression
    • data-val-regex="Error message"
    • data-val-regex-pattern="The regular expression (e.g. ^[a-z]+$)"
  • Required
    • data-val-required="Error message"
  • StringLength
    • data-val-length="Error message"
    • data-val-length-max="Maximum number of characters"

There are also a few validation methods you can use that don’t seem to have a counterpart in System.ComponentModel.DataAnnotation. In fact you get a list of all the available client side validation methods by typing (for example in chrome) dev tools console: $.validator.unobtrusive.adapters. Here’s the list of the ones that don’t have a matching attribute: date, digits, number, url, length, remote, password.

How To Generating SEO (and user) friendly URLs in ASP.NET MVC

How To Generating SEO (and user) friendly URLs in ASP.NET MVC

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC Hosting. In today’s blog post I would like to demonstrate how to generate “friendly” URLs in your ASP.NET applications. Friendly not just in the sense that someone can look at it and figure out what the URL is pointing to, but more importantly friendly for search engines.

Right now you may probably ask what difference it makes to search engines like Google what the URL of a page is? Surely a computer does not care? Well you would be sort of right, but the thing is that having keywords you are trying to rank for in the URL of a page, does indeed make a difference.

There are many things which play a role in how Google determines the ranking of a web page, and no one can say for certain exactly how big a part each of those factors play. What most people agree on however is that having the keywords you want a page to rank for in the URL of the page does indeed help with the ranking of the page.

In this blog post I am going to show you how to generate URLs in your application which is more SEO – and user – friendly.

Generate URLs

In my sample application I have created a fictitious product database which displays a listing of products, and allows a user to click on a specific product to navigate to the details page for that product.

My product class is fairly simple:

On the product listing page I simply display a list of products:

product-listing

And when the user clicks on a specific product they are navigated to a product details page:

product-detail-with-id

Take a look at the URL which we are generating:

product-id-url

It is just a normal URL as you get in most ASP.NET MVC application which passes along the ID of particular database row to the controller action.

We want to have something which is more user friendly. Something which at least also contains the name of our product. To generate a friendly URL I have created a new method on my Product class which generates a proper “slug” (or URL) for the product details page:

And I have also updated my listing page to use the slug as the route parameter instead of the Id as it did before:

Now when I navigate to the product detail page I can see that we have a proper “friendly” URL which contains the name of the product:

product-detail-with-slug-but-error

Parameter binding

But also notice that we have a new error. ASP.NET MVC is complaining that it was expecting an id route parameter, but could not find it. This is because the Details action on my controller is expecting an integer value for the id parameter:

But instead of an integer, the {id} part of our route now contains a string. The MVC framework is trying to convert the string to an integer, but cannot do it and therefore it is passing a null value along, and then complains that the id parameter cannot contain a null value.

To fix this error we need to modify the RouteData for the route to fix up the value of the id route parameter.

I have created a new class called SeoFriendlyRoute that inherits from Route and have overridden the GetRouteData method to clean up the id parameter. In my implementation I call the base GetRouteData method and check if the route data is not null, in which case it means that I have a match for my route.

In this case I simple check whether the id parameter is present and if it is I use a regular expression to extract the first part of the URL that contains the actual numerical ID, and I assign that numerical value to the id route value:

And the last bit is to add a new route for the path /products/details/{id} to use my new SeoFriendlyRoute route class:

And now when I refresh the page, the parameters are bound correctly as only the numeric part of the product URL that contains the actual product ID is passed along as the id parameter:

product-detail-with-slug

How to Structure The Application in ASP.NET MVC Areas

How to Structure The Application in ASP.NET MVC Areas

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. This week I discovered a difficulty related to structuring an ASP.NET MVC web applications one advancement crew was dealing with. The things they have been trying to do was quite straightforward: to create a folder framework each having their particular subfolders for View/Controller/Scripts/CSS and so on. The appliance assets like JS/CSS etc. were not getting rendered properly. The difficulty was owing to NET.config file lying underneath the subfolder, which when moved to the Views folder below that subfolder things went good. The purpose of this post just isn’t to debate regarding the specifics of that difficulty and it is solution.But to discuss regarding how we will very easily framework our ASP.NET MVC Web application as per distinct modules, which is an clear need for just about any big application.

ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions operates good to get a smaller sized software. But for relatively bigger a single there is a necessity to customise.The framework also offers adequate provisions for the same.You’ll be able to have your personal controller manufacturing facility to get custom methods to making the controller classes and custom see engine for finding the rendering the sights. But when the necessity would be to structure the applying to distinct subfolders as per modules or subsites I believe using “Area” in ASP.NET MVC will likely be useful to make a streamlined software.

You can add a area to some ASP.NET MVC undertaking in Visual Studio as shown beneath.

aspm

as1

Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.

res

The code (auto generated) for the SalesAreaRegistration class is shown below:

 System.Web.Mvc.AreaRegistration may be the summary base class use registering the places to the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) must be overriden to sign up the realm by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the mandatory information (like Routes) required to sign-up the area.

In Global.asax.cs Application_Start occasion we must RegisterAllAreas() technique as demonstrated under:

 The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.

e

I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

 Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);