How to make textbox optional in MVC

Viewed 289

I've been trying to figure out how I can make a textbox optional. I've tried the javascript method (value).removeAtt('required'). I've also tried removing [Required] from ViewModel it worked however when you do enter text it comes up in the database as null. What other ways can i approach this.

Viewmodel

[Required]
[Display(Name="comment")]
public string comment{get; set;]

Controller

public ActionResult Edit(QuestionToAnswerViewModel questionToAnswerVm)
        {
            var questionToAnswer = _questionAnswerService.GetAnswerById(questionToAnswerVm.QuestionId);

            if (ModelState.IsValid)
            {

                if(questionToAnswerVm.AdditionalComment != null)
                {
                    questionToAnswer.Comment = questionToAnswerVm.AdditionalComment;
                }
                else
                {
                    questionToAnswer.Comment = null;
                }

View

    <div id ="additionalComment" class="form-group">
        @Html.LabelFor(model => model.AdditionalComment,htmlAttributes: new { @class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.AdditionalComment,new { @class = "form-control"})

        </div>
    </div
2 Answers

If you still specify required attribute in Models/View Models Specify this n your model file as

public string? comment {get;set;}

also you can specify this line in your global.asax file in application_onstart event

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Few things to check

  1. Remove required from model.
  2. Check if id matches with view and model. Put a break point in controller and check if value is getting passed from view to controller.
Related