Required value in Html.TextBoxFor
Solution 1
I don't know why but when i delete the space between =
and @
<td>@Html.TextBoxFor(m =>(m.Code), new { @Value [email protected], @required = "required"})</td>
it works
Solution 2
Use
@Html.ValidationMessageFor(m => m.Code)
for validating the code property.and code Property should be define like this-
[Required]
public string Code{ get; set; }
and for setting the value in code Textbox.You can set it in controller like this.
Model.Code="fffff";
and on the view use like this-
<td>@Html.TextBoxFor(m =>(m.Code), new { @Value = @Model.Code)</td>
@Html.ValidationMessageFor(m => m.Code)
and yes dont forgot to include the validation Js i.e
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
Try it:-
Solution 3
you don't need the parens
@Html.TextBoxFor(m => m.Code, new { @class = "txtCode" })
if you set code on the controller side the value will be put in the text box
Related videos on Youtube
Lamloumi Afif
Hi, I am a Software Development Engineer with a genuine interest in .Net framework. I enjoy reading books and practising sport. LinkedIn Viadeo
Updated on July 09, 2022Comments
-
Lamloumi Afif almost 2 years
I need to put the value of a
TextBox
required like this :<td>@Html.TextBoxFor(m =>(m.Code), new { @required = "required"})</td>
It works. But if i set a default value to the
TextBox
<td>@Html.TextBoxFor(m =>(m.Code), new { @Value = @Model.Code, @required = "required"})</td>
An empty value becomes accepted despite the generation of this Html code
<td><input id="Code" name="Code" required="required" type="text" value="fff "></td>
- What is the source of this problem?
- How can i fix it?
-
Jeandre Pentz over 10 yearsYes your validation should be in your models like in this post. It will become a mess if you do it on the view, especially when you want to do custom error messages.
-
Cloud about 5 yearsHow to do this dynamically rather than on submit?