I am currently trying to implement a behavior for DataAttributes (Maxlength[int] or StringLength[int]), where it would add a "maxlength" attribute inside the tag (textarea) along with its "int" value. I have already performed some research, and the closest answers I obtained were this post and that question.
However, I hope to go one step further. I already know that StringLength adds "data-val-length-max" and "data-val-length" attributes to the tag.
I spent a lot of time trying to implement it in JavaScript by using logic
if tag has data-val-length-max attribute
add maxlength attribute to this tag and assign its value equal to data-val-length-max value
However, the way my project is set up is it is constantly jumps back and forth with different Javascript files, so I wanted to change the approach (hopefully, without messing with .js files).
Inside my .cshtml file, there are lines like this
@Html.myLabelFor(model => model.Project.ProjectDescription, new { @title = "Enter a description for this project" })
@Html.TextAreaFor(model => model.Project.ProjectDescription, new { @class = "textfield_Paragraph", @id = "ProjectDescription" })
@Html.ValidationMessageFor(model => model.Project.ProjectDescription)
I learned that it successfully adds maxvalue if I make it like this:
@Html.TextAreaFor(model => model.Project.ProjectDescription, new { @class = "textfield_Paragraph", @id = "ProjectDescription", @maxlength = 50 })
However, I do not want to take such approach of adding this line to every single line of code in solution; I want to turn it into reusable code, that would dynamically perform such action to every variable within TextAreaFor inside the .cs file, which are marked like following:
[MaxLength(50)]
[Display(Name = "Project Description")]
public string ProjectDescription { get; set; }
So I was thinking of implementing it by using the logic
if metadata has a MaxLength flag
htmlAttributes += " ', @maxlength = ' + maxLengthValue <-- 50 in that case"
So, physically it will still be
@Html.TextAreaFor(model => model.Project.ProjectDescription, new { @class = "textfield_Paragraph", @id = "ProjectDescription" })
while the final value that will be loaded will be
@Html.TextAreaFor(model => model.Project.ProjectDescription, new { @class = "textfield_Paragraph", @id = "ProjectDescription", @maxlength = 50 })
I want to know if something like this is even possible to implement, so I know beforehand if I should continue thinking in that direction.
Again, links I have posted above were the closest answers I could get, so I am curious if it is as far as I can get, or there is even more room to improve. My huge preference would be NOT touching .js files unless I absolutely HAVE to.
Aucun commentaire:
Enregistrer un commentaire