MAS
MAS

Reputation: 43

asp.net mvc 5, validation for not required fields(optional fields)

i've a form that some of the fields is not required to be filled or optional fields in asp.net mvc 5 application.

i've tried this things but, warning message for "this fields is required", keep showing.

[Required(AllowEmptyStrings = true)]
public string country { get; set; }

adding htmlAttribute
@required = false

Data Model

public class LoginViewModel
{
    ...

    public string country { get; set; }

    ...
}

public class CountryLists
{
    ...
    public string CountryName { get; set; }
    public string CountryCode { get; set; }
    ...
}

Index.cshtml

@using (Html.BeginForm("Save", "SignUp", FormMethod.Post, new { name = "signUpForms", id = "signUpForm", @class = "registerLogin-form" }))
{
...
    if (Model.MembershipProgram.StsSignUpCountry)
    {
        <div class="form-group col-12">
           @Html.DropDownListFor(m => m.country, 
          new SelectList(Model.CountryLists, "CountryCode", "CountryName"),
          "Select Country",
            new
            {
                id = "select_country",
                @class = "form-control"
            })
        </div>
    }
...
<button type="submit" id="register-submit-btn" class="btn btn-primary pull-right active" name="command" value="Save">
            @ViewBag.JoinNow <i class="m-icon-swapright m-icon-white"></i>
</button>
}

enter image description here

Upvotes: 0

Views: 2120

Answers (3)

शेखर
शेखर

Reputation: 17614

Problem could be CountryCode.
Check your model if it is an integer then it should be like

 public int? CountryCode{ get; set; }

You will have a model with two properties at least

  public int CountryCode{ get; set; }
  public string CountryName{ get; set; }

You have mentioned in your code as below

new SelectList(Model.CountryLists, "CountryCode", "CountryName"),

Upvotes: 0

Ravi Mali
Ravi Mali

Reputation: 119

might be duplicat of : ASP .NET MVC Disable Client Side Validation at Per-Field Level

may be it helps: If your are using MVC4 and latest version you can write it as

 @{ Html.EnableClientValidation(false); }
 if (Model.MembershipProgram.StsSignUpCountry)
 {
    <div class="form-group col-12">
       @Html.DropDownListFor(m => m.country, 
      new SelectList(Model.CountryLists, "CountryCode", "CountryName"),
      "Select Country",
        new
        {
            id = "select_country",
            @class = "form-control"
        })
    </div>
}
@{ Html.EnableClientValidation(true); }

Upvotes: 0

Sumit Singh
Sumit Singh

Reputation: 92

Just make value= false in web.config for ClientValidationEnabled

<appSettings><add key="ClientValidationEnabled" value="false" /></appSettings>

Upvotes: 1

Related Questions