So let's say I have a small model object that contains a string that's required and has a max length of 50:
public class ObjectModel
{
[Required]
[MaxLength(50)]
public string Name { get; set; }
}
I need to create a custom HTML helper where I can pass in a string (in this case, ObjectModel.Name) and if it's required, create an HTML input element with class "required".
Right now, I'm trying to work with:
public static HtmlString Input(string label)
{
return new HtmlString("<input type=\"text\" />");
}
So in my Razor view, if I do something like @InputHelper.Input(Model.Name)
, I can't access the attributes. My question is, how do I structure my HTML helper class to accept a Model property along with its attributes?
So I've made further progress, but I'm still not experienced enough to navigate through expressions to get what I want. Right now, I have:
@InputHelper.Input(m => Model.Title.TitleName, "titlename2", "Title Name")
The second and third parameters are irrelevant to this question. And in the helper method, I have:
public static HtmlString Input(Expression<Func<string, Object>> expression, string id, string label)
But when I go to debug the code, there are so many objects and properties to sift through that I have no idea where my Required and MaxLength attributes are, if they're even in there.