2

I want to display alert message box when the account model is invalid. How should i gonna do this in controller in Asp.Net Core MVC? Here is my Controller's code

    [HttpPost]
    public IActionResult Index(Account model)
    {
        if (model.ID != null && model.PassWord != null)
        {
            using (var db = new AccountDBContext())
            {
                var account = db.Account.FirstOrDefault(
                                a => a.ID.Equals(model.ID) && a.PassWord.Equals(model.PassWord)
                              );

                if(account != null)
                    return RedirectToAction("Index", "Main");       

            }
            //I want to display error msg box...here like "Check ID or PW".
            ModelState.AddModelError("", "Error");

        }


        return View();
    }

I searched the way but there is no "Page" identifier or "Response.write()" Method in this controller class.... How should i gonna do?

p.s The way that i checked model's validation like that is right way? (I used a model and check it's partial properties, instead using view model )

1 Answer 1

7

Define the error in your controller:

ModelState.AddModelError("Error", "Check ID");

And then display it in the view:

@if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count > 0)
{
    <div class="alert alert-
       <strong>Error!</strong> danger">@ViewData.ModelState["Error"].Errors.First().ErrorMessage
    </div>
}

EDIT

To show an alert box, add some javascript in your view, the following uses jquery:

<head>
    <script type="text/javascript">
        @if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count > 0)
        {
            <text>
            $(document).ready(function() {
                alert('@ViewData.ModelState["Error"].Errors.First().ErrorMessage');
            });
            </text>
        }
    </script>
</head>
Sign up to request clarification or add additional context in comments.

4 Comments

OP has asked how to do it using an alert message box
Thanks for answering! but i put below if it is not valid. <script> alert('@Html.ValidationMessage("Error")')</script> Then there is an error occured like this. <span class="field-validation-valid" data-valmsg-for="Error" data-valmsg-replace="true"></span>
I fixed a small bug, I just tested it and should do what you want ;)
Oh Thanks a lot!! (p.s : May i ask ViewData.ModelState["Error"].Errors.Count meaning?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.