Geeks With Blogs

News profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers "free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.

Donate Bitcoins



Check out Elapser from T3rse!


Programming and Learning from SD

In order to get placeholder or maxLength or other Html attributes to work with the Html.EditorFor methods, you need to create an override file in Views\Shared\EditorTemplates\string.cshtml.

@{
    // make placeholder work
    // http://stackoverflow.com/questions/5824124/html5-placeholders-with-net-mvc-3-razor-editorfor-extension
    // from [Display(Prompt =
    IDictionary<string, object> attributes = new Dictionary<string, object>();
    if (!string.IsNullOrEmpty(ViewData.ModelMetadata.Watermark))
    {
        attributes.Add("placeholder", ViewData.ModelMetadata.Watermark);
    }

    // http://setiabud.blogspot.com/2010/08/stringlength-validator-into-maxlength.html
    IEnumerable<ModelValidator> validators = ModelValidatorProviders.Providers.GetValidators(ViewData.ModelMetadata, ViewContext);
    ModelClientValidationRule stringLengthRule = validators.SelectMany(v => v.GetClientValidationRules()).FirstOrDefault(m => m.ValidationType == "length");
    if (stringLengthRule != null && stringLengthRule.ValidationParameters.ContainsKey("max"))
    {
        attributes.Add("maxlength", stringLengthRule.ValidationParameters["max"]);
    }

        // this approach would grab it from the  @Html.EditorFor(model => model.FirstName, new { MaxLength = 10})
        // http://stackoverflow.com/questions/1625327/editorfor-and-html-properties
        // if (ViewData["maxLength"] != null)
        // {
        //    attributes.Add("maxLength", (int)ViewData["maxLength"]);
        // }
}
<span>
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, attributes)
</span>
Posted on Wednesday, December 19, 2012 9:41 AM MVC | Back to top


Comments on this post: MVC 4 string.cshtml override

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Aligned | Powered by: GeeksWithBlogs.net | Join free