gpt4 book ai didi

c# - ASP.NET MVC5 在 View 中的标签中显示异常错误消息可能吗?

转载 作者:行者123 更新时间:2023-12-03 08:26:50 26 4
gpt4 key购买 nike

在经典的 ASP.NET 中,我在 .aspx 页面上放置了一个标签,当抛出错误时,例如通过 try ... catch block ,我使标签可见并将错误消息绑定(bind)到标签 Text属性(property)。

但在 MVC 中,这似乎是不可能的。我在网上找到的所有示例都显示了如何重定向到专用的错误 View 。但我想直接在错误发生的页面或模型对话框中解决错误。

这是否可能以及如何在 MVC (4/5) 中执行此操作?

最佳答案

将错误消息传递到 ViewBag 中,然后在 View 中显示消息。

Controller

public ActionResult Index()
{
try
{
//Do something
}
catch (Exception e)
{
ViewBag.Error = e.Message;
}
return View();
}

查看
@if(ViewBag.Error != null)
{
<label>@ViewBag.Error</label>
}

关于c# - ASP.NET MVC5 在 View 中的标签中显示异常错误消息可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38868558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com