0

I have a ProductsController with an Index method. This Index method contains a .Where() part that looks through the database with the users input. (for example: "Apples, Banana's, Exotic, etc.") When there are no results found it throws an error: "Sequence contains no elements" which is logical.

When the errors throws, I want it to be displayed in an AlertBox. I have followed this thread but I can't seem to get the error to the View.

My Index Method:

        public ActionResult Index(string item = "APPE", int amount = 0)
        {
            var CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
            ViewData["Amount"] = amount; 
            //Uses the Logged in Username to match the items related to it's CompanyNr
            var LoggedUser = Convert.ToInt32(User.Identity.Name);
            Dr dr = _context.Dr.Where(x => x.CompanyNr == LoggedUser).First();
            var itemCheck = item != null ? item.ToUpper() : "";
            try
            {
                // It throws the Error right here. because there are no elements matching in _context.Th
                var currentCat = _context.Th.Where(x => x.CategoryCode.Contains(itemCheck)).First();

                Console.WriteLine("My currentCat is: " + currentCat.ToString());
                if (itemCheck == "")
                {
                    ViewData["Category"] = "All Products";
                }
                else
                {
                    //Displays the Categories on the Users chosen language
                    ViewData["Category"] = CurrentCulture switch
                    {
                        "en-US" => currentCat.NameEnglish,
                        "nl-NL" => currentCat.NameDutch,
                        "de-DE" => currentCat.NameGerman,
                        "da-DK" => currentCat.NameFrench,
                        _ => currentCat.NameEnglish,
                    };

                var SearchItem = _context.Products
                    .Where(x => x.CompanyNr == LoggedUser)
                    .Where(x => x.CategoryCode.Contains(itemCheck));

                #section A copy of the products for the users shopping cart called newProducts
                #endregion
                return View(newProducts);
                }

            catch (Exception ex)
            {
                //ex.Message contains "Sequence contains no elements"
                ModelState.AddModelError("Error", ex.Message);
                //return View("Index");
                return View("Index");
                
            }
        }

My View

        <div id="FilterList">
            <ul>
                <li>
                    <form method="get" asp-action="Index" asp-controller="Products">
                        <input type="hidden" name="item" value="" />
                        <button type="submit">@Localizer["Show All"]</button>
                    </form>
                </li>
            </ul>
            <ul>
                @foreach (var item in ViewData["Main_Items"] as IEnumerable<Project.Models.DataBase.Th>)
                {

                <li>
                    <form method="get" asp-action="Index" asp-controller="Products">
                        @switch (CurrentCulture)
                    {
                        case "nl-NL":
                            <input type="hidden" name="item" value="@item.CategoryCode.Trim()" />
                            <button type="submit">@item.NameDutch</button> break;
                        case "en-US":
                            <input type="hidden" name="item" value="@item.CategoryCode.Trim()" />
                            <button type="submit">@item.NameEnglish</button> break;
                        case "de-DE":
                            <input type="hidden" name="item" value="@item.CategoryCode.Trim()" />
                            <button type="submit">@item.NameGerman</button> break;
                        case "da-DK":
                            <input type="hidden" name="item" value="@item.CategoryCode.Trim()" />
                            <button type="submit">@item.NameFrench</button> break;
                        default:
                            <input type="hidden" name="item" value="@item.CategoryCode.Trim()" />
                            <button type="submit">@item.NameEnglish</button>
                        break;
                     }
                    </form>
                </li>            
                }
            </ul>
        </div>

The JavaScript that is supposed to show the AlertBox

/*If the model is not valid and there is more than 0 "Error", Show an Alert with it's error*/
@if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count > 0)
{
    <text>
    $(document).ready(function () {
        alert('@ViewData.ModelState["Error"].Errors.First().ErrorMessage');
        /*It's not logging anything..*/
        console.log('@ViewData.ModelState["Error"].Errors.First().ErrorMessage');
    });
    </text>
}

I feel like i'm missing something important which I am not finding. I hope I have given enough explanation in both the code and my summary to help find the solution.

1 Answer 1

1

After my test, I found that there is no problem with your code, and it works very well for me. You can check your code based on my simple example below.

View:

  <form asp-action="Create">
        <div class="form-group">
            <label asp-for="Id" class="control-label"></label>
            <input asp-for="Id" class="form-control" />
        </div>
        <div class="form-group">
            <label asp-for="Name" class="control-label"></label>
            <input asp-for="Name" class="form-control" />
        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
@section Scripts {

<script type="text/javascript">
       @if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count > 0)
        {
            <text>
            $(document).ready(function () {
                alert('@ViewData.ModelState["Error"].Errors.First().ErrorMessage');
                /*It's not logging anything..*/
                console.log('@ViewData.ModelState["Error"].Errors.First().ErrorMessage');
            });
            </text>
        }
</script>
}

Action:

 public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Create(Student student)
    {
        try
        {
            var m = _context.Student.Where(c => c.Name.Contains("bb")).First();
            return View();
        }
        catch (Exception ex)
        {

            ModelState.AddModelError("Error", ex.Message);
            return View("Create");
        }
 
    }

You can check as follow steps:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

When I inspect my @section Scripts it doesn't show the entire function that i've written. the @if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count > 0) makes it so that the entire function disappears from the website
So what you want to check is whether your ViewData.ModelState.IsValid is true.
This means that @if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count> 0) will only display the code in js if the conditions are met, and will not be displayed if the conditions are not met
Ooohhh I see. that makes sense, thank you for clarifying that

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.