iDipa
iDipa

Reputation: 345

Display custom error message in ASP .Net 5, MVC 6

I have one method which is calling api method. That api method contains SQL statements of insert, update, delete. But when any error is thrown from stored procedure, How to display in front as error message. I am using ASP .NET 5 and MVC 6. My method is like below :

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Method(Model model)
{
    string url = ConfigurationSettingHelper.BaseUrl + "apiurl";

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.PostAsJsonAsync<Model>(url, model);

        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();
            var Msg = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(data);

            if (!string.IsNullOrEmpty(Convert.ToString(Msg)))
            {
                //Here code to display error message.
            }
        }
    }
    return View();
}

Help me to display Msg variable string message on page.

Thank You

Upvotes: 0

Views: 5362

Answers (2)

Ian Auty
Ian Auty

Reputation: 847

There are a few ways to achieve this I think.

1) Use a ViewModel which could store a List<string> Errors that you can pass back to your view. Although to do this for all views would be very repetitive and not easy to maintain.

2) Use TempData to store the error messages instead of in your ViewModel. This way, you could check in your _Layout.cshtml if there are any items in TempData and display them in any way you wish (this would happen to all of your views).

3) Use toastr.js and the TempData approach to display a nice toast instead. Begin by implementing a POCO which includes an Enum for the different response types available in toastr.js i.e Error, Info, Success, Warning. Then, create a BaseController.cs file which your controllers will implement, see below for an example of this.

Next in your Controllers, you can call CreateNotification(AlertType.Error, "This is a test message.", "Error");

Finally, you need to put logic into your _Layout.cshtml file to make use of the notifications. Make sure you add a reference to toastr.js and its CSS file, and see below for an example of how to wire it up:

Full example:

Notification.cs

```

public class Alert
{
    public AlertType Type { get; set; }
    public string Message { get; set; }
    public string Title { get; set; }
}

public enum AlertType
{
    Info,
    Success,
    Warning,
    Error
}

```

BaseController.cs

public override void OnActionExecuting(ActionExecutingContext context)
    {            
        GenerateNotifications();    

        base.OnActionExecuting(context);
    }

public void CreateNotification(Notification.AlertType type, string message, string title = "")
    {
        Notification.Alert toast = new Notification.Alert();
        toast.Type = type;
        toast.Message = message;
        toast.Title = title;

        List<Notification.Alert> alerts = new List<Notification.Alert>();

        if (this.TempData.ContainsKey("alert"))
        {
            alerts = JsonConvert.DeserializeObject<List<Notification.Alert>>(this.TempData["alert"].ToString());
            this.TempData.Remove("alert");
        }

        alerts.Add(toast);

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All
        };

        string alertJson = JsonConvert.SerializeObject(alerts, settings);

        this.TempData.Add("alert", alertJson);
    }

    public void GenerateNotifications()
    {
        if (this.TempData.ContainsKey("alert"))
        {               
            ViewBag.Notifications = this.TempData["alert"];
            this.TempData.Remove("alert");
        }
    }

Layout.cshtml

@if (ViewBag.Notifications != null)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All
    };
    List<Notification.Alert> obj = JsonConvert.DeserializeObject<List<Notification.Alert>>(ViewBag.Notifications, settings);

    foreach (Notification.Alert notification in obj)
    {
        switch (notification.Type)
        {
            case Notification.AlertType.Success:
                <script type="text/javascript">toastr.success('@notification.Message', '@notification.Title');</script>
                break;
            case Notification.AlertType.Error:
                <script type="text/javascript">toastr.error('@notification.Message', '@notification.Title');</script>
                break;
            case Notification.AlertType.Info:
                <script type="text/javascript">toastr.info('@notification.Message', '@notification.Title');</script>
                break;
            case Notification.AlertType.Warning:
                <script type="text/javascript">toastr.warning('@notification.Message', '@notification.Title');</script>
                break;
        }
    }
}

Upvotes: 5

Matheno
Matheno

Reputation: 4142

You can use Response.Write(str) both in code-behind and on the .ASPX page:

<%
Response.Write(str)
%>

Using Response.Write() in code-behind places the string before the HTML of the page, so it's not always useful.

You can also create a server control somewhere on your ASPX page, such as a label or literal, and set the text or value of that control in code-behind:

.ASPX:

<asp:Label id="lblText" runat="server" />

Code-behind:

lblText.Text = "Hello world"

Outputs in HTML:

<span id="lblText">Hello World</span>

If you don't want s added, use a literal:

<asp:Literal id="litText" runat="server" />

And set the value attribute of the literal instead of the text attribute:

litText.Value = "Hello World"

Upvotes: 0

Related Questions