One can use jquery to mask the inputs.There are quiet a few good plugins available for this e.g. http://digitalbush.com/projects/masked-input-plugin/
Only drawback to this approach is we need to link jquery function for each input to be masked.
Alternate approach can be creating a data annotation for mask and use it on model/viwModel.
Step 1: Create a mask attribute
Step 2:Create a partial view in EditorTemplates and add an extension method for ViewDataDictionary
to get the attribute for the property
Step 3: Register this new extension in web.config of Views folder.
Step 4: Use this attribute on Model/ViewModels property.
Only drawback to this approach is we need to link jquery function for each input to be masked.
Alternate approach can be creating a data annotation for mask and use it on model/viwModel.
Step 1: Create a mask attribute
Common\CustomAttributes\MaskAttribute.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MvcLists.Common.CustomAttributes
- {
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class MaskAttribute:Attribute,IMetadataAware
- {
- private string _mask = string.Empty;
- public MaskAttribute(string mask)
- {
- _mask = mask;
- }
- public string Mask
- {
- get { return _mask; }
- }
- private const string ScriptText = "<script type='text/javascript'>" +
- "$(document).ready(function () {{" +
- "$('#{0}').mask('{1}');}});</script>";
- public const string templateHint = "_maskedInput";
- private int _count;
- public string Id
- {
- get { return "maskedInput_" + _count; }
- }
- internal HttpContextBase Context
- {
- get { return new HttpContextWrapper(HttpContext.Current); }
- }
- public void OnMetadataCreated(ModelMetadata metadata)
- {
- var list = Context.Items["Scripts"] as IList<string> ?? new List<string>();
- _count = list.Count;
- metadata.TemplateHint = templateHint;
- metadata.AdditionalValues[templateHint] = Id;
- list.Add(string.Format(ScriptText, Id, Mask));
- Context.Items["Scripts"] = list;
- }
- }
- }
Views\Shared\EditorTemplates\_mask.cshtml
- @using MvcLists.Common.CustomAttributes
- @model System.String
- @{ var maskedInput = ViewData.GetModelAttribute<MaskAttribute>();
- if (maskedInput != null)
- {
- <div class="editor-label">
- @Html.LabelForModel()
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(m => m, new { id = ViewData.ModelMetadata.AdditionalValues[MaskAttribute.templateHint] })
- </div>
- }
- }
Common\MvcExtensions\ViewDataExtensions.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MvcLists.Common.MvcExtensions
- {
- public static class ViewDataExtensions
- {
- public static TAttribute GetModelAttribute<TAttribute>(this ViewDataDictionary viewData,bool inherit=false) where TAttribute:Attribute
- {
- if(viewData==null) throw new ArgumentException("ViewData");
- var containerType = viewData.ModelMetadata.ContainerType;
- return
- ((TAttribute[])
- containerType.GetProperty(viewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof (TAttribute),
- inherit)).
- FirstOrDefault();
- }
- }
- }
Common\HtmlHelpers\HtmlHelpers.cs
- public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
- {
- var scripts = htmlHelper.ViewContext.HttpContext.Items["Scripts"] as IList<string>;
- if (scripts != null)
- {
- var builder = new StringBuilder();
- foreach (var script in scripts)
- {
- builder.AppendLine(script);
- }
- return new MvcHtmlString(builder.ToString());
- }
- return null;
- }
Web.config
- < system.web.webPages.razor >
- < host factoryType= "System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
- < pages pageBaseType= "System.Web.Mvc.WebViewPage" >
- < namespaces >
- < add namespace= "System.Web.Mvc" />
- < add namespace= "System.Web.Mvc.Ajax" />
- < add namespace= "System.Web.Mvc.Html" />
- < add namespace= "System.Web.Routing" />
- < add namespace= "MvcLists.Common.MvcExtensions" />
- </ namespaces >
- </ pages >
- </ system.web.webPages.razor >
Models\Person.cs
- public class Person
- {
- [Tooltip("Enter First Name")]
- public string FirstName { get; set; }
- [Tooltip("Enter Last Name")]
- public string LastName { get; set; }
- [Tooltip("Enter SSN")]
- [Mask("999-99-9999")]
- public string SSN { get; set; }
- [Tooltip("Enter Age")]
- [Mask("99")]
- public string Age { get; set; }
- [Mask("999-999-9999")]
- [Tooltip("Enter Phone")]
- public string Phone { get; set; }
- [Mask("99999-9999")]
- [Tooltip("Enter Zip Code")]
- public string ZipCode { get; set; }
- [Mask("9999-9999-9999-9999")]
- [Tooltip("Enter Credit Card")]
- public string CreaditCard { get; set; }
- }
Views\Person\Index.cshtml
- @using (Html.BeginForm("Index","Person"))
- {
- @Html.ValidationSummary(true)
- <fieldset>
- <legend>Person</legend>
- <div class="editor-label">
- @Html.LabelFor(model => model.FirstName)
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(model => model.FirstName,new{title=@Html.TooltipFor(x=>x.FirstName)})
- @Html.ValidationMessageFor(model => model.FirstName)
- </div>
- <div class="editor-label">
- @Html.LabelFor(model => model.LastName)
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(model => model.LastName,new{title=Html.TooltipFor(x=>x.LastName)})
- @Html.ValidationMessageFor(model => model.LastName)
- </div>
- @Html.EditorFor(x => x.SSN)
- @Html.EditorFor(x => x.Age)
- @Html.EditorFor(x => x.Phone)
- @Html.EditorFor(x => x.CreaditCard)
- @Html.EditorFor(x => x.ZipCode)
- <p>
- <input type="submit" value="Create" />
- </p>
- </fieldset>
- }
4 comments:
where does the IHtmlString RenderScripts comes into place?
That I generally use to add dynamic script blocks.
Don't know if you got my last comment but I couldn't see where you use the renderscript and what class the method belongs to.
I will update my sample code which uses RenderScripts function.
Post a Comment