我认为有几种方法可以实现这一目标。
1) 使用可以存储 List<string> Errors 的 ViewModel,您可以将其传递回您的视图。尽管对所有视图都这样做会非常重复且不易维护。
2) 使用 TempData 来存储错误消息,而不是在您的 ViewModel 中。这样,您可以检查 _Layout.cshtml 中是否有 TempData 中的任何项目,并以您希望的任何方式显示它们(这将发生在您的所有视图中)。
3) 使用 toastr.js 和 TempData 方法来显示一个漂亮的 toast。首先实现一个 POCO,其中包括一个用于 toastr.js 中可用的不同响应类型的枚举,即错误、信息、成功、警告。然后,创建一个您的控制器将实现的 BaseController.cs 文件,请参阅下面的示例。
接下来在你的控制器中,你可以调用 CreateNotification(AlertType.Error, "This is a test message.", "Error");
最后,您需要将逻辑放入 _Layout.cshtml 文件中以使用通知。确保您添加了对 toastr.js 及其 CSS 文件的引用,并在下面查看如何连接它的示例:
完整示例:
Notification.cs
```
public class Alert
{
public AlertType Type { get; set; }
public string Message { get; set; }
public string Title { get; set; }
}
public enum AlertType
{
Info,
Success,
Warning,
Error
}
```
BaseController.cs
public override void OnActionExecuting(ActionExecutingContext context)
{
GenerateNotifications();
base.OnActionExecuting(context);
}
public void CreateNotification(Notification.AlertType type, string message, string title = "")
{
Notification.Alert toast = new Notification.Alert();
toast.Type = type;
toast.Message = message;
toast.Title = title;
List<Notification.Alert> alerts = new List<Notification.Alert>();
if (this.TempData.ContainsKey("alert"))
{
alerts = JsonConvert.DeserializeObject<List<Notification.Alert>>(this.TempData["alert"].ToString());
this.TempData.Remove("alert");
}
alerts.Add(toast);
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
string alertJson = JsonConvert.SerializeObject(alerts, settings);
this.TempData.Add("alert", alertJson);
}
public void GenerateNotifications()
{
if (this.TempData.ContainsKey("alert"))
{
ViewBag.Notifications = this.TempData["alert"];
this.TempData.Remove("alert");
}
}
Layout.cshtml
@if (ViewBag.Notifications != null)
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
List<Notification.Alert> obj = JsonConvert.DeserializeObject<List<Notification.Alert>>(ViewBag.Notifications, settings);
foreach (Notification.Alert notification in obj)
{
switch (notification.Type)
{
case Notification.AlertType.Success:
<script type="text/javascript">toastr.success('@notification.Message', '@notification.Title');</script>
break;
case Notification.AlertType.Error:
<script type="text/javascript">toastr.error('@notification.Message', '@notification.Title');</script>
break;
case Notification.AlertType.Info:
<script type="text/javascript">toastr.info('@notification.Message', '@notification.Title');</script>
break;
case Notification.AlertType.Warning:
<script type="text/javascript">toastr.warning('@notification.Message', '@notification.Title');</script>
break;
}
}
}