【问题标题】:Displaying ModelState Error in an AlertBox using JavaScript使用 JavaScript 在 AlertBox 中显示 ModelState 错误
【发布时间】:2021-06-03 09:57:37
【问题描述】:

我有一个带有 Index 方法的 ProductsController。此 Index 方法包含一个 .Where() 部分,该部分使用用户输入查看数据库。 (例如:“Apples、Banana's、Exotic 等”) 当没有找到结果时,它会抛出一个错误:“序列不包含元素”,这是合乎逻辑的。

当错误抛出时,我希望它显示在 AlertBox 中。 我关注了this thread,但我似乎无法将错误传递给视图。

我的索引方法:

        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");
                
            }
        }

我的观点

        <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>

应该显示警报框的 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>
}

我觉得我错过了一些我没有找到的重要东西。我希望我在代码和摘要中都给出了足够的解释,以帮助找到解决方案。

【问题讨论】:

    标签: javascript c# asp.net-core-mvc


    【解决方案1】:

    经过我的测试,我发现你的代码没有问题,对我来说效果很好。您可以根据我下面的简单示例检查您的代码。

    查看:

      <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>
    }
    

    行动:

     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");
            }
     
        }
    

    您可以按照以下步骤进行检查:

    【讨论】:

    • 当我检查我的@section Scripts 时,它没有显示我编写的整个函数。 @if (!ViewData.ModelState.IsValid &amp;&amp; ViewData.ModelState["Error"].Errors.Count &gt; 0) 使整个功能从网站上消失
    • 那么你要检查的是你的ViewData.ModelState.IsValid是不是真的。
    • 这表示@if (!ViewData.ModelState.IsValid &amp;&amp; ViewData.ModelState["Error"].Errors.Count&gt; 0)只有满足条件才会显示js中的代码,不满足条件就不显示
    • 哦,我明白了。这是有道理的,谢谢你澄清这一点
    猜你喜欢
    • 1970-01-01
    • 2013-06-07
    • 2020-01-25
    • 2020-03-10
    • 2011-03-09
    • 2020-08-29
    • 2017-07-28
    • 2019-10-21
    • 1970-01-01
    相关资源
    最近更新 更多