I'm developing a MVC 5
app with the SweetAlert 2 plugin.
My Goal: When an error occurs anywhere in my app I'd like to display a (centralized, sweetalert) modal dialog with a title/message.
I created a PartialView called "_ModalError" and referenced this in the bottom of my main, shared "_Layout" view. Basically so this partial view will be enabled for every page.
I then created a simple Error class...
namespace MyApp.Models
{
public class MyError
{
public string ErrorTitle { get; set; }
public string ErrorMessage { get; set; }
}
}
I was thinking that, whenever I get an error, I would instantiate a new MyError object, set the appropriate ErrorTitle and ErrorMessage properties, then set ViewBag.Error to this MyError object.
private MyError err = new MyError();
err.ErrorMessage = "Your information was not valid. Please re-check everything.";
err.ErrorTitle = "Error!";
ViewBag.Error = err;
Then, in javascript, whenever the _ModalError (the page) loads, it would look to see if ViewBag.Error exists. If so, an error occurred, so display it. Here's what I have so far....
<script>
$(function() {
if (@ViewBag.Error != null) {
swal(
@ViewBag.Error.ErrorTitle,
@ViewBag.Error.ErrorMessage,
'error'
);
};
</script>
The problem is that when the page first loads I get this error when it hits the viewbag code...
Cannot perform runtime binding on a null reference.
I'm trying to access ViewBag
but apparently it doesn't exist at first, which makes sense. But, checking to see if it's null isn't really working. Do you know why this is? Any suggestions? Is this a faulty, crazy, or over-kill solution?
******** SOLUTION ********
Here's the solution. Thanks to Stephen Muecke (below) for the Json.Encode advice! I hope this is helpful to someone else!
<script>
$(function() {
var error = @Html.Raw(Json.Encode(ViewBag.Error));
if (error != null) {
swal(
error.ErrorTitle,
error.ErrorMessage,
'error'
);
}
})