Nevi
Nevi

Reputation: 328

Compare Attribute Not Working

I have password and confirm password fields with compare attribute but it's bugged? tried everything updated everything via NuGet package manager the password is still not matching even if i input '123456', wonder what should i do?

enter image description here

  public class AccountsViewModel
    {
        public class Register
        {
            [Required]
            public string Username { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Compare("Password")]
            [DataType(DataType.Password)]
            public string ConfirmPassword { get; set; }

        }

    }

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "id,username,password")] AccountsViewModel.Register viewModel)
{
    if (ModelState.IsValid)
    {
        account account = new account();
        db.accounts.Add(account).username = viewModel.Username;
        db.accounts.Add(account).password = viewModel.Password;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    return View(viewModel);
}

View

@model trainingmvc.Models.AccountsViewModel.Register

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm("Create", "Accounts", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Username, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Web Config

   <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

Bundles

  bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));

Upvotes: 1

Views: 716

Answers (1)

user3559349
user3559349

Reputation:

Your POST method has a [Bind] attribute

public async Task<ActionResult> Create([Bind(Include = "id,username,password")] AccountsViewModel.Register viewModel)

which excludes the models ConfirmPassword property from binding, therefore its value of it is null which is invalid (it does not match the value of Password) so a ModelState error is added.

AccountsViewModel is a view model and a view model should never need a Bind attribute (because a view model only contains properties that are edited in the view). Just remove the attribute so all properties are bound and you model will be valid.

Upvotes: 2

Related Questions