Required value in Html.TextBoxFor

I need to specify a value TextBoxlike this:

<td>@Html.TextBoxFor(m =>(m.Code), new { @required  = "required"})</td>

It works. But if I set the default value forTextBox

<td>@Html.TextBoxFor(m =>(m.Code), new { @Value = @Model.Code, @required  = "required"})</td>

An empty value becomes accepted despite the creation of this HTML

<td><input id="Code" name="Code" required="required" type="text" value="fff       "></td>
  • What is the source of this problem?
  • How can i fix this?
+4
source share
3 answers

I don’t know why, but when I remove the space between =and@

<td>@Html.TextBoxFor(m =>(m.Code), new { @Value =@Model.Code, @required  = "required"})</td>

working

+6
source

Use

@Html.ValidationMessageFor(m => m.Code)

to check the properties of the code. And the Property code should be defined as follows:

 [Required]
 public string Code{ get; set; }

and to set the value in the textbox code. You can install it in the controller as follows.

Model.Code="fffff";

and in view mode -

<td>@Html.TextBoxFor(m =>(m.Code), new { @Value = @Model.Code)</td>
 @Html.ValidationMessageFor(m => m.Code)

Js i.e

 <script src="/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

: -

+8

@Html.TextBoxFor(m => m.Code, new { @class = "txtCode" })

if you set the code on the controller side, the value will be placed in the text box

+1
source

All Articles