0

I need to validate some fields from a form, I'm not using any front-end language to perform this, I'm getting the information from the ActionResultI need to show some message!

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ResetPassword(string user, string hash)
    {
        string old = Request.Form["oldpassword"];
        string password = Request.Form["password"];
        string repeat = Request.Form["repeatpassword"];


        if(String.IsNullOrEmpty(old) || String.IsNullOrEmpty(password) || String.IsNullOrEmpty(repeat))
        {
            "show a dialog".
        }
Nathiel Barros
  • 685
  • 2
  • 11
  • 25
  • You can pass the message value to a JS modal popup: https://stackoverflow.com/questions/13183630/how-to-open-a-bootstrap-modal-window-using-jquery. Just set modal popup text based from viewmodel then, e.g. `$(".modal-body").text('@Model.Message')`. – Tetsuya Yamamoto Jul 13 '17 at 02:56
  • 1
    If your making a normal POST then add a `ModelStateError` and return the view so it is sisplayef in your `@Html.ValidationSummary()` placeholder. –  Jul 13 '17 at 03:01
  • `ModelState.AddModelError` method is also valid, at least use `ValidationSummary` or `ValidationMessage` in proper place: `$(".modal-body").text('@Html.ValidationSummary()')`. – Tetsuya Yamamoto Jul 13 '17 at 03:24
  • It works without using `@Html.EditorFor`? I'm using ` – Nathiel Barros Jul 13 '17 at 03:26
  • Thanks guys! Worked fine! `ModelState.AddModelError` – Nathiel Barros Jul 13 '17 at 03:31
  • Not valid question there few step to do the validate form fields. please use useful pattern which is easy for you. @Nathiel Barros – Shahzad Khan Jul 13 '17 at 05:40

1 Answers1

2

Here is a good way to do it:

View:

@model Testy20161006.Controllers.ResetPasswordViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>IndexPage2</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
    @{
        if (ViewBag.ShowDialog != null && ViewBag.ShowDialog == true)
        {
            <script type="text/javascript">
                $(function () {
                    $("#aModal").modal('show');
                })
            </script>
        }
    }
    @using (Html.BeginForm("ResetPassword", "Home"))
    {
        <div>
            <table>
                <tr>
                    <td>@Html.LabelFor(r => r.oldPassword)</td>
                    <td>@Html.TextBoxFor(r => r.oldPassword)</td>
                </tr>
                <tr>
                    <td>@Html.LabelFor(r => r.newPassword)</td>
                    <td>@Html.TextBoxFor(r => r.newPassword)</td>
                </tr>
                <tr>
                    <td>@Html.LabelFor(r => r.repeatNewPassword)</td>
                    <td>@Html.TextBoxFor(r => r.repeatNewPassword)</td>
                </tr>
            </table>
        </div>
        <input type="submit" value="submit" />
    }
    @*modal*@
    <div class="modal fade" id="aModal" tabindex="-1" role="dialog" aria-labelledby="aModalLabel"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="aModalLabel">Warning</h4>
                </div>
                <div class="modal-body">
                    Old Password, New Password, or repeat Password is empty.
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Controller/ViewModel:

public class ResetPasswordViewModel
{
    public string oldPassword { get; set; }
    public string newPassword { get; set; }
    public string repeatNewPassword { get; set; }
}

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult ResetPassword(ResetPasswordViewModel resetPasswordViewModel)
    {
        if (String.IsNullOrEmpty(resetPasswordViewModel.oldPassword) ||
            String.IsNullOrEmpty(resetPasswordViewModel.newPassword) ||
            String.IsNullOrEmpty(resetPasswordViewModel.repeatNewPassword)
            )
        {
            //show dialog
            ViewBag.ShowDialog = true;
        }

        return View("IndexPage2", resetPasswordViewModel);
    }

    public ActionResult IndexPage2()
    {   //start page specified in routeconfig.cs
        return View();
    }
kblau
  • 2,094
  • 1
  • 8
  • 20
  • Let's say that I need to validate a more few things? The `ViewBag.ShowDialog = true;` will show the logic inside of cshtml, how to distinguish ? – Nathiel Barros Jul 14 '17 at 03:57
  • 1
    More viewbags would work. The best way is to put [required] attribute on the required properties in the view model. In the action, check ModelState.Valid and if valid write to db or reset password, otherwise show the view again. The view will automatically say which fields did not meet validation. Html.ValidationSummary(false) will show all errors and Html.ValidationMessageFor(model => model.FieldName) will put an error by the fields. – kblau Jul 14 '17 at 05:57