0

I'm working on an ASP.Net MVC 5 project uisng razor views.

I have multiple textarea fields in a form using html helpers.

Everything seems to be working ok however the labels for textareas don't show the "*" to denote a required field like the other fields do. Is there a special reason for this? How do I get it to do that?

My model looks like this (only relevant info shown):

    [Required, DisplayName("Agreed Action")]
    public string AgreedActionText { get; set; }

My View looks like this:

<div class="form-group">
  @Html.LabelFor(model => model.AgreedActionText, new { @class = "col-xs-12 col-sm-2  col-md-2 control-label" })
  <div class="col-xs-12 col-sm-10 col-md-10">
    @Html.TextAreaFor(model => model.AgreedActionText, new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.AgreedActionText)
  </div>
</div>    

Working example:

Model:

[Required, DisplayName("Action Title")]        
public string ActionShort { get; set; }

View:

<div class="form-group">
  @Html.LabelFor(m => m.ActionShort, new { @class = "col-xs-12 col-sm-4 col-md-4 control-label" })
  <div class="col-xs-12 col-sm-8 col-md-8">
    @Html.TextBoxFor(m => m.ActionShort, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.ActionShort)
  </div>
</div>

This works:

<label class="col-xs-12 col-sm-2 col-md-2 control-label" for="AgreedActionText">Agreed   Action Text<span style="color:red"> *</span></label>

But it's not really the solution I was after, I want the helper to automatically know it's a required field and add the asterix like it does with text boxes and other input fields.

punkologist
  • 721
  • 5
  • 14

3 Answers3

1

You can create your own html helper for that. This may help :

How can I override the @Html.LabelFor template?

Html inside label using Html helper

Community
  • 1
  • 1
Mukesh Modhvadiya
  • 2,178
  • 2
  • 27
  • 32
  • Yeah this will do it. I ended up just manually creating the label without the helper. I might come back and change it later but I am under pressure to get this in prod asap so probably don't have time. – punkologist Jun 05 '14 at 01:38
0
<style type="text/css">
.requiredlabel :after 
{
    content: "*";
    font-weight: bold;
    color: red; 
}
</style>
  @Html.Label("Title", new { @id = "lbltitleName", @class = "control-label requiredlabel " })
-3

I've had a quick look at the ASP.NET website and noticed the following snipper of code in the validation tutorial:

[Required(ErrorMessage = "Price is required")]

So in your instance:

[Required(ErrorMessage = "*"), DisplayName("Agreed Action")]

Now, I understand that the above will not show until the user tries to submit the form with missing content however the implementation is handled entirely by the MVC Framework.

I hope this leads you closer to what you are after.

Jamie Keeling
  • 9,806
  • 17
  • 65
  • 102