Reputation: 656
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 )
Upvotes: 2
Views: 35229
Reputation: 15180
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>
Upvotes: 7