0

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

2
  • You mean like Response.Write(Msg); ? Commented Jan 18, 2016 at 12:22
  • Yes, like that only but that is not supported in ASP.Net 5. Any other method? Commented Jan 18, 2016 at 12:33

2 Answers 2

5

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

hey can you provide any working example of your 3rd solution??
I've expanded the example to show the Class and Enum you need to add. The only thing left is to add the CSS/JS includes to your View for toastr.js.
Great answer helped a lot - but I have an issue - if you return View(model) - with error - the method OnActionExecuting is not fired - how fix it? Thx
I'm not sure I follow you fully - what do you mean return the View() with error? Are you saying an exception is being thrown somewhere in your code before the View is returned?
0

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"

2 Comments

I dn't have aspx page. view page is .cshtml page
I suggest you to follow a tutorial

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.