Thursday, 4 August 2016

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

Start by creating a custom attribute implementing this interface:
public class PlaceHolderAttribute : Attribute, IMetadataAware
{
    private readonly string _placeholder;
    public PlaceHolderAttribute(string placeholder)
    {
        _placeholder = placeholder;
    }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["placeholder"] = _placeholder;
    }
}
And then decorate your model with it:
public class MyViewModel
{
    [PlaceHolder("Enter title here")]
    public string Title { get; set; }
}
Next define a controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
}
A corresponding view:
@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Title)
    <input type="submit" value="OK" />
}
And finally the editor template (~/Views/Shared/EditorTemplates/string.cshtml):
@{
    var placeholder = string.Empty;
    if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("placeholder"))
    {
        placeholder = ViewData.ModelMetadata.AdditionalValues["placeholder"] as string;
    }
}
<span>
    @Html.Label(ViewData.ModelMetadata.PropertyName)
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder = placeholder })
</span>

No comments:

Post a Comment