我在AspNet Core 3.1中有一个Razor Page,可以在其中单击一个按钮,并且会出现Bootstrap警报。这是jquery-效果很好:
<script>
$(document).ready(function () {
$('#btnSubmit').click(showError);
$('#linkClose').click(function () {
$('#errorAlert').hide('fade');
});
});
function showError() {
$('#errorAlert').show('fade');
setTimeout(function () {
$('#errorAlert').hide('fade');
}, 5000);
}
if (@Model.ShowError) {
showError();
}
</script>
我想做的是,在记录错误后,从try catch块的“代码隐藏”中触发了相同的警报:
在这里我要这样做:
[TempData]
public string ErrorMessage { get; set; }
[BindProperty]
public bool ShowError { get; set; } = false;
公共异步任务OnGetAsync(bool id){ShowError = id;
try
{
var ret = ManipulateMyFile(file)
}
catch (Exception ex)
{
Log.Error("File being used - {ex}", ex);
ErrorMessage= "File being used";
return Redirect("/Admin/LearningTasks/Index/true");
}
return Redirect("/Admin/LearningTasks/Index/false");
}
在实现这一目标方面的任何帮助。
您可以在ViewBag中设置一个变量,然后在视图中检查它以触发javascript函数。但是,如果执行此操作,请确保将其默认设置为false
,否则可能会导致视图错误。
在控制器中
ViewBag.ShowError = false;
try
{
var ret = ManipulateMyFile(file)
}
catch (IOException ex)
{
Log.Error("File being used - {ex}", ex);
ViewBag.ShowError = true;
}
然后在“剃刀”视图中
<script>
var doShowError = @ViewBag.ShowError.ToString().ToLower();
$(document).ready(function () {
$('#btnSubmit').click(showError);
$('#linkClose').click(function () {
$('#errorAlert').hide('fade');
});
// show the error
if (doShowError) {
showError();
}
});
</script>