i'm trying to show multiple error messages in view by toastr , for user register page.
I passed a list of error messages to View with TempData["errors"]
but i don't know how to show a list of string (for errors)
I did this for a successful message and the code is as follows
register.cshtml
@if (TempData["success"] != null)
{
<script>
$(document).ready(function() {
var message = '@(TempData["success"])';
toastr.options = {
"rtl": true,
"closeButton": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-left",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
toastr.success(message);
});
My suggestion is that:
You could turn the list to string in your controller as follow:
var err = new List<string>() { "error1", "error2", "error3" };
var er = string.Join(",", err.ToArray());
TempData["errors"] = er;
then replace ","with <br/>
in your javascript codes as follow :
var message1 = '@TempData["errors"]';
var message2 = message1.replaceAll(',', '<br/>');
toastr.error(message2, 'Errors');
Result:
but if you turn the list to string as follow :
controller:
var err = new List<string>() { "error1", "error2", "error3" };
var er1 = string.Join("<br/>", err.ToArray());
TempData["error?"] = er1;
Js:
var message3 = '@TempData["error?"]';
toastr.error(message3, 'Errors');
Result:
If you want send Individual error message: controller:
var err = new List<string>() { "error1", "error2", "error3" };
TempData["error!"] = err;
Js:
var message4 = @Html.Raw(Json.Serialize(TempData["error!"]));
message4.forEach(x => toastr.error(x));
Result: