如何在 Razor Pages 中向用户打印消息

How to print a message to user in Razor Pages

我正在使用 Razor Pages 创建 Web 应用程序,但我 运行 遇到了问题。我试图在抛出异常时向用户发送消息。我正在想象类似于 System.Windows.Forms 中的 MessageBox class 的东西。关于这是否可能或如何做的任何想法?感谢任何帮助。

try
{
    double oneone = Convert.ToDouble(Project.projectServicesCost);
}
catch (Exception e)
{
    //Throw message to user saying projectServicesCost is not in the correct 
    //format and therefore couldn't convert to double
}

这是我的代码中的一个示例。

您可以在 ViewBag 上使用来自 Bootstrap 和 return 的模态异常并检查何时不为空并显示模态

[HttpPost]
public ActionResult Save(int? id){
  UserViewModel model = new UserViewModel();
  if(id == null){
    ViewBag.Exception = "Please select an ID";
    return View();
  }
  model.User = context.Users.FisrtOrDefault(a => a.id == id);
  return View(model);
}

<script>
$(document).ready(function(){
  var exception = @String.IsNullOrEmpty(ViewBag.Exception).ToString().ToLower();
  if(!exception){
    $("#modal-body").text("@ViewBag.Exception");
    $("#modal").modal("show");
  }
});
</script>

或使用来自 js 的警报

<script>
    $(document).ready(function(){
      var exception = @String.IsNullOrEmpty(ViewBag.Exception).ToString().ToLower();
      if(!exception){
        alert("@ViewBag.Exception");
      }
    });
 </script>

您可以使用一些库,例如 NToastNotify

您可以按照以下步骤来实现它:

1.Install 使用包控制台管理器的 NToastNotify 包:

Install-Package NToastNotify

2.Configure NToastNotify 服务和

services.AddRazorPages().AddNToastNotifyNoty();

3.Add 中间件:

app.UseNToastNotify();

4.Add _Layout 页面中的视图:

@await Component.InvokeAsync("NToastNotify")

5.Dependency注入IToastNotification就可以使用了

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly IToastNotification _toastNotification;

    public IndexModel(ILogger<IndexModel> logger, IToastNotification toastNotification)
    {
        _logger = logger;
        _toastNotification = toastNotification;
    }

    public void OnGet()
    {
        try
        {
            throw new NullReferenceException();
        }
        catch
        {
            _toastNotification.AddErrorToastMessage("Some Error Message");
        }
    }
}

结果:

详情请参考: https://github.com/nabinked/NToastNotify