Reputation: 111
I'm trying to add a required to my TextAreaFor, but it won't give the error message when i post it. I'm trying to do it on the followinng line:
@Html.TextAreaFor(model => model.Content, new { htmlAttributes = new { @class = "form-control", required = "" } })
And this is my full code:
@using (Html.BeginForm("_Create", "Comments", FormMethod.Post))
{
@Html.HiddenFor(m => m.ThreadId)
<div class="form-group">
<div class="col-md-10">
@Html.TextAreaFor(model => model.Content, new { htmlAttributes = new { @class = "form-control", required = "" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger"})
</div>
</div>
<div class="form-group">
<div>
<input type="submit" value="Post" class="btn btn-default" />
</div>
</div>
}
Upvotes: 0
Views: 5988
Reputation: 31
If anyone wanst to do it with html attribute,
@Html.TextAreaFor(model => model.Content, new { required = "required", htmlAttributes = new { @class = "form-control"} })
Upvotes: 3
Reputation: 9854
@Html.TextAreaFor(model => model.Content, new { htmlAttributes = new { @class = "form-control", required = "" } })
Should be:
@Html.TextAreaFor(model => model.Content, new { @class = "form-control", required = "required" })
Or if you want to explicitly name the parameter your anonymous object is for:
@Html.TextAreaFor(model => model.Content, htmlAttributes: new { @class = "form-control", required = "" } })
But, if you do not use data-annotation, it could be even easier this way:
<textarea id="Content" name="Content" required class="form-control">@Model.Content</textarea>
(id
attribute may be optional, depending on your usages.)
Side note: I tend to minimize uses of html helpers methods. For me, MVC is also about letting you control very precisely the browser client code, which is imo better done by writing it yourself. WebForm is, on this subject, about hiding most of browser client code handling.
Using extensively html helpers, built-in validation logic, and so on, may cause you to lose the precise control of how your page should work.
Upvotes: 0
Reputation: 5109
You don't need required as a html attribute. It should be a data annotation on the model.
[Required]
public string Content { get; set; }
Upvotes: 1