asp.net-mvcasp.net-mvc-4asp.net-mvc-5asp.net-mvc-controller

MVC 4 Displaying error message


I have a requirement where an action link with query string parameter has been implemented from a controller view say CreateFilter which navigates to a different controller say Create where I parse the query string parameter and gets the data through SP and display it in the Create View.

But I have a scenario that when the SP doesn't return any data then the Create View shouldn't render and the user should be able to see the error message "No records found" in the same View where he is currently (CreateFilter).

Can any one please let me know how to achieve this scenario ? Any help would be greatly appreciated.

Thanks Vimalkumar


Solution

  • Set the error message in TempData and do a redirect back to the CreateFilter action. There, you can check if that value is in TempData and display it if so.

    TempData["CreateFilterError"] = "No records found";
    return RedirectToAction("CreateFilter");
    

    Then, in your CreateFilter view:

    @if (TempData["CreateFilterError"] != null)
    {
        <p>@TempData["CreateFilterError"]</p>
    }
    

    Alternatively, you can pass something in the query string with the redirect:

    return RedirectToAction("CreateFilter", { error = true });
    

    Then, handle it much the same in your view:

    @if (Request["error"] as bool? ?? false)
    {
        <p>No records found</p>
    }