Search code examples
.netasp.net-mvctextboxdata-annotations

How to programmatically create textbox based on mvc view model object?


Is there a way to programmatically create a textbox based on a view model object? Let me elaborate. Take for example, a standard ViewModel object like password.

public class PassWordViewModel
{
    [DataType(DataType.Password)]
    [MaxLength(10)]
    public string Password { get; set; }
}

Now take for example, a textbox control built programmatically:

TextBox textBox = new TextBox();
textBox.TextMode = TextBoxMode.Password;
textBox.MaxLength = 10;

How do I programmatically create a textbox which contains all of the properties that are set on my model object?

TextBox textBox = [CREATE TEXTBOX FROM MY PASSWORD 
VIEWMODEL OBJECT CONTAINING ALL THE DATA ANNOTATED 
PROPERTIES]

Solution

  • It's unusual to have to do this, but it's possible all the same.

    You first need to create an instance of HtmlHelper<PasswordViewModel> in your controller:

    var viewContext = new ViewContext(ControllerContext, new NullObjectView(), ViewData, TempData, TextWriter.Null);
    var helper = new HtmlHelper<PassWordViewModel>(viewContext, new ViewPage());
    

    As you can see, there is a NullObjectView class in there, which is as follows:

    public class NullObjectView : IView
    {
        public void Render(ViewContext viewContext, TextWriter writer)
        {
    
        }
    }
    

    Then create the textbox using System.Web.Mvc.Html.InputExtensions.TextBoxFor():

    var textbox = InputExtensions.TextBoxFor(helper, x => x.Password);
    

    This returns an MvcHtmlString, which will contain the full textbox output of:

    <input data-val="true" data-val-maxlength="The field Password must be a string or array type with a maximum length of '10'." data-val-maxlength-max="10" id="Password" name="Password" value="" type="text">