.net MVC验证在提交前显示错误消息

0s7z1bwu  于 2022-12-20  发布在  .NET
关注(0)|答案(1)|浏览(120)

我有一个视图和一个模型,模型包含问题和一个用于存储特定问题结果的属性。我无法让它验证问题,它总是在提交时通过模型验证测试(在控制器内部)。我检查了jquery,jqueryvalidate和jqueryunobrtusive都包含在那个顺序中,我试着在表单内部和外部移动摘要,没有帮助。提交后它显示为好像所有都是有效的,并且消息在呈现视图时呈现。

public class Result
    {
        [Required]
        public int ResultID { get; set; }

        [Required]
        public string Text { get; set; }
    }

 public class Question
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public Result Result{ get; set; }
    }
<div>
    @Html.ValidationSummary(true, "", new { @class = "text-danger" });
</div>

@using (Html.BeginForm("Submit", "post", FormMethod.Post, new { id = "Form" }))
{
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

    for (int i = 0; i < Model.Count; i++)
    {
        var item = Model[i];

            <div>

                <div>
                    @item.Text
                    @Html.TextBoxFor(m => m[i].Result.Text, null, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m[i].Result.Text)
                    @Html.HiddenFor(m => m[1].Result.ResultID )
                </div>
            </div>
        }
    }

    <div>
        <input type="submit" value="Submit"/>
    </div>
}
       public ActionResult Index()
       {           
           List<Question> Questions = GetAllQuestions();

           return View("View", Questions);
       }

        public ActionResult Submit(List<Question> sQuestions)
        {

            if (!ModelState.IsValid)
            {
                return View("Index", );
            }
6l7fqoea

6l7fqoea1#

提交按钮似乎不在表单中。
去掉多余的右大括号,它应该可以工作了。抱歉没有早点发现。我刚刚做了一个快速的代码比较。
视图应如下所示:

@using (Html.BeginForm("Submit", "Home", FormMethod.Post, new { id = "Form" }))
{
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

    for (int i = 0; i < Model.Count; i++)
    {
        var item = Model[i];

        <div>

            <div>
                @item.Text
                @Html.TextBoxFor(m => m[i].Result.Text, null, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m[i].Result.Text)
                @Html.HiddenFor(m => m[i].Result.ResultID)
            </div>
        </div>
    }
    <div>
        <input type="submit" value="Submit" />
    </div>
}

相关问题