Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting an attribute from a parameter in an HTML helper
    text
    copied!<p>So let's say I have a small model object that contains a string that's required and has a max length of 50:</p> <pre><code>public class ObjectModel { [Required] [MaxLength(50)] public string Name { get; set; } } </code></pre> <p>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". </p> <p>Right now, I'm trying to work with:</p> <pre><code> public static HtmlString Input(string label) { return new HtmlString("&lt;input type=\"text\" /&gt;"); } </code></pre> <p>So in my Razor view, if I do something like <code>@InputHelper.Input(Model.Name)</code>, 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?</p> <p>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:</p> <p><code>@InputHelper.Input(m =&gt; Model.Title.TitleName, "titlename2", "Title Name")</code> </p> <p>The second and third parameters are irrelevant to this question. And in the helper method, I have:</p> <p><code>public static HtmlString Input(Expression&lt;Func&lt;string, Object&gt;&gt; expression, string id, string label)</code></p> <p>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. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload