简体   繁体   English

使用 JavaScript 在 AlertBox 中显示 ModelState 错误

[英]Displaying ModelState Error in an AlertBox using JavaScript

I have a ProductsController with an Index method.我有一个带有 Index 方法的 ProductsController。 This Index method contains a.Where() part that looks through the database with the users input.此 Index 方法包含 a.Where() 部分,该部分使用用户输入查看数据库。 (for example: "Apples, Banana's, Exotic, etc.") When there are no results found it throws an error: "Sequence contains no elements" which is logical. (例如:“Apples、Banana's、Exotic 等”)当没有找到结果时,它会抛出一个错误:“Sequence contains no elements”,这是合乎逻辑的。

When the errors throws, I want it to be displayed in an AlertBox.当错误抛出时,我希望它显示在 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应该显示警报框的 JavaScript

/*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.我希望我在代码和摘要中都给出了足够的解释,以帮助找到解决方案。

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:您可以按照以下步骤进行检查:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM