Click here to Skip to main content
15,881,248 members
Articles / Web Development / XHTML

Form validation with ASP.NET MVC using the IErrorDataInfo interface

Rate me:
Please Sign up or sign in to vote.
4.78/5 (6 votes)
13 Aug 2009CPOL1 min read 23.7K   15   2
In this article, I will explore an alternative method of implementing validation logic. I will show you how to perform validation by using the IErrorDataInfo interface.

Introduction

I will explore an alternative method of implementing validation logic with ASP.NET MVC. I will show you how to perform validation by using the IErrorDataInfo interface.

Background

I have already shown in my previous article how to perform form validation with ASP.NET MVC. In this article, I will explore an alternative method of implementing validation logic.

Using the code

Here is the IDataErrorInfo interface:

C#
public interface IDataErrorInfo
{
    // Properties
    string Error { get; }
    string this[string columnName] { get; }
}

We will modify the last article that implements the IErrorDataInfo interface. To implement the IDataErrorInfo interface, we must create a partial class. Our tblComment partial class is shown below:

C#
public partial class tblComment : IDataErrorInfo
{
    private Dictionary<string,> _errors = new Dictionary<string,>();

    partial void OnNameChanging(string value)
    {
        if (string.IsNullOrEmpty(value.Trim()))
            _errors.Add("Name", "Name is required.");
    }

    partial void OnEmailChanging(string value)
    {
        if (string.IsNullOrEmpty(value.Trim()))
            _errors.Add("Email", "Email is required.");
    }

    partial void OnMessageChanging(string value)
    {
        if (string.IsNullOrEmpty(value.Trim()))
            _errors.Add("Message", "Message is required.");
    }

    #region IDataErrorInfo Members

    public string Error
    {
        get { return string.Empty; }
    }

    public string this[string columnName]
    {
        get
        {
            if (_errors.ContainsKey(columnName))
                return _errors[columnName];
            return string.Empty;
        }
    }

    #endregion
}

One thing to note, when the Entity Framework generates an entity class, the Entity Framework adds partial methods to the class automatically. The Entity Framework generates the OnChanging and OnChanged partial methods that correspond to each property of the class. We will modify our UserCommentController class as shown below:

C#
public class UserCommentController : Controller
{
    private CommentEntities _db = new CommentEntities();

    [AcceptVerbs("GET")]
    public ActionResult UserComment()
    {
        return View(new tblComment());
    }

    [AcceptVerbs("POST")]
    public ActionResult UserComment([Bind(Exclude = "CommentID")] 
                                     tblComment commentToCreate)
    {
        // Validate
        if (!ModelState.IsValid)
            return View();

        // Add to database
        try
        {
            _db.AddTotblComment(commentToCreate);
            _db.SaveChanges();
        
            return RedirectToAction("UserComment");
        }
        catch
        {
            return View();
        }
    }
}

The ASP.NET MVC framework creates the instance of the tblComment passed to the UserComment() action by using a model binder. The model binder is responsible for creating an instance of the tblComment object by binding the HTML form fields to an instance of the tblComment object. Now, I will run the project and it will display the User Comment view as shown below:

Image 1

Summary

In this article, we explored form validation with ASP.NET MVC using the IErrorDataInfo interface.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
chungtayeunhau26-Jun-10 2:54
chungtayeunhau26-Jun-10 2:54 
NewsIt's IDataErrorInfo not IErrorDataInfo (see title) Pin
Andrei Ion Rînea23-Aug-09 22:41
Andrei Ion Rînea23-Aug-09 22:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.