Geeks With Blogs

News Please visit me at my new blog!!

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.

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
    // from [Display(Prompt =
    IDictionary<string, object> attributes = new Dictionary<string, object>();
    if (!string.IsNullOrEmpty(ViewData.ModelMetadata.Watermark))
        attributes.Add("placeholder", ViewData.ModelMetadata.Watermark);

    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})
        // if (ViewData["maxLength"] != null)
        // {
        //    attributes.Add("maxLength", (int)ViewData["maxLength"]);
        // }
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, attributes)
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: