This is my controller:
public async Task<IActionResult>ActiveEmailAccount(EmailActiveAccountViewModel active)
{
if (ModelState.IsValid)
{
var result = await _userService.ActiveAccount(active);
switch (result)
{
case ActiveEmailResult.Error:
ModelState.AddModelError("CustomError", "You Have Error ");
break;
case ActiveEmailResult.NotActive:
ModelState.AddModelError("CustomError", "You Are not Active. ");
break;
case ActiveEmailResult.Success:
ModelState.AddModelError("CustomError", "You Are Active ");
break;
}
ViewData["Active"] = result;
}
return View(active);
}
I want to show result of View data in view. I know it is
<p> @(ViewData["Active"] </P>
I want to know how can I show these results in different status with different class?
for example if was success: with class="alert-success"
if was not active with class alert-danger.....
Inside the switch-case statement in your action you can set a ViewData
entry with the alert class for each case:
public async Task<IActionResult> ActiveEmailAccount(EmailActiveAccountViewModel active)
{
if (ModelState.IsValid)
{
var result = await _userService.ActiveAccount(active);
switch (result)
{
case ActiveEmailResult.Error:
ModelState.AddModelError("CustomError", "You Have Error ");
ViewData["AlertClass"] = "alert-danger";
break;
case ActiveEmailResult.NotActive:
ModelState.AddModelError("CustomError", "You Are not Active. ");
ViewData["AlertClass"] = "alert-warning";
break;
case ActiveEmailResult.Success:
ModelState.AddModelError("CustomError", "You Are Active ");
ViewData["AlertClass"] = "alert-success";
break;
}
// this is not needed for this scenario
//ViewData["Active"] = result;
}
return View(active);
}
Then in your view you can use Html.ValidationMessage
html helper to get the model state message and ViewData
to get the alert class:
<div class="alert @ViewData["AlertClass"]">
@Html.ValidationMessage("CustomError")
</div>
Razor solution:
You can use a switch-case statement inside your view:
@switch ((ActiveEmailResult)ViewData["Active"])
{
case ActiveEmailResult.Error:
<div class="alert alert-danger">@Html.ValidationMessage("CustomError")</div>
break;
case ActiveEmailResult.NotActive:
<div class="alert alert-warning">@Html.ValidationMessage("CustomError")</div>
break;
case ActiveEmailResult.Success:
<div class="alert alert-success">@Html.ValidationMessage("CustomError")</div>
break;
}