Monday, September 29, 2014

Decorate MVC models with attributes to make CRUD operations against them require less code all-in-all.

Like so:

using System.ComponentModel.DataAnnotations;
namespace Finance.Models
{
   public class Profile
   {
      [Display(Name = "full name...")]
      [Required(ErrorMessage = "Please enter your name.")]
      [StringLength(20, MinimumLength = 4, ErrorMessage = "Please enter at least 4
            characters")]
      public string Name { get; set; }
      
      [Display(Name = "email address...")]
      [Required(ErrorMessage = "Please enter your email.")]
      [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-+.']\w+)*\.\w+([-+.']\w+)*$",
            ErrorMessage = "Please enter a valid email.")]
      public string Email { get; set; }
   }
}

 
 

The attributes will bias how the model behaves at a form as seen here:

 
 

Our example has the following Controller:

using System.Web.Mvc;
using Finance.Models;
using Finance.Utilities;
namespace Finance.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         Profile profile = Utility.GetCurrentProfile();
         return View(profile);
      }
      
      [HttpPost]
      public ActionResult Index(Profile profile)
      {
         Utility.UpdateCurrentProfile(profile);
         return View();
      }
   }
}

 
 

Our example has the following view:

@model Finance.Models.Profile
@{
   Layout = null;
}
<html>
   <head>
      <title>Whatever</title>
   </head>
   <body>
      @using (Html.BeginForm("Index", "Home"))
      {
         <article>
            <h1>Update yourself:</h1>
            
            <h2>@Html.LabelFor(m => m.Name)</h2>
            <section>
               @Html.TextBoxFor(m => m.Name)
            </section>
            <section style="color:#FF0000; padding-bottom: 40px;">
               @Html.ValidationMessageFor(m => m.Name)
            </section>
            
            <h2>@Html.LabelFor(m => m.Email)</h2>
            <section>
               @Html.TextBoxFor(m => m.Email)
            </section>
            <section style="color:#FF0000; padding-bottom: 40px;">
               @Html.ValidationMessageFor(m => m.Email)
            </section>
            
            <input type="submit" />
         </article>
      }
   </body>
</html>

No comments:

Post a Comment