【问题标题】:Passing value for required property at Controller, but still ModelState.IsValid is false在 Controller 传递所需属性的值,但 ModelState.IsValid 仍然为 false
【发布时间】:2023-03-04 21:01:02
【问题描述】:

我有一个部分视图可以在我的主视图上为我的文章模块发表评论以获取文章详细信息。用于评论的模型具有三个必填字段,ID(身份字段)、ArticleIdCommentText。 (我使用的是 Razor 语法)

我尝试在Create Action 中将ArticleId 传递给控制器​​。

public ActionResult Create(ArticleComment articlecomment, string AID)
{

    articlecomment.ArticleId = AID;    //this is required

    if (User.Identity.IsAuthenticated)
    {
        articlecomment.UserId = WebSecurity.CurrentUserId.ToString();
    }
    else
    {
        articlecomment.UserId = Constants.Anonymus;
    }

    articlecomment.CommentDate = DateTime.Now;

    if (ModelState.IsValid)
    {
        db.ArticleComment.Add(articlecomment);
        int success = db.SaveChanges();
        if (success > 0)
        {
            return Content("<script language='javascript' type='text/javascript'>alert('Comment added successfully.');window.location.href='" + articlecomment.ArticleId + "';</script>");
        }
        else
        {
            return Content("<script language='javascript' type='text/javascript'>alert('Posting comment has failed, please try later.');window.location.href='" + articlecomment.ArticleId+ "';</script>");
        }
    }

    return PartialView(articlecomment);
}

ModelState.IsValid 仍然返回 false。我使用了以下代码,发现ModelStateArticleId 设为空。

foreach (var modelStateValue in ViewData.ModelState.Values)
{
    foreach (var error in modelStateValue.Errors)
    {
        // Do something useful with these properties
        var errorMessage = error.ErrorMessage;
        var exception = error.Exception;
    }
}

我还考虑使用 ViewBag 使用隐藏字段为 ArticleId 设置值,但没有找到任何工作代码。我尝试了以下操作:

@Html.HiddenFor(model => model.ArticleId, new { @value = ViewBag.Article })

 @Html.HiddenFor(model => model.ArticleId, (object)ViewBag.Article)

我要发表评论的“ParticalView”是:

@model Outliner.Models.ArticleComment

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)



        <div class="editor-label">
           @* @Html.HiddenFor(model => model.ArticleId, new { @value = ViewBag.Article })
            @Html.HiddenFor(model => model.ArticleId, (object)ViewBag.Article)*@
            @Html.LabelFor(model => model.Comment) &nbsp;&nbsp;&nbsp;
            <span class="error">@Html.ValidationMessageFor(model => model.Comment)</span>  
        </div>

            @Html.TextAreaFor(model => model.Comment)        

            <input type="submit" value="Post" />        

}

这就是我在“ArticalDetail”视图(我的主视图)上调用这个局部视图的方式:

 @Html.Action("Create", "ArticleComment")

我之前已经在控制器上为视图传递了必填字段值,但我面临 PartialView 的问题。我做错了什么,我该如何做?

尝试后编辑

当 Satpal 和 Fals 引导我找到一个方向时,我尝试了他们的建议,并尝试了以下操作:

TryUpdateModel(articlecomment);

还有

TryUpdateModel<ArticleComment>(articlecomment);

还有

TryValidateModel(articlecomment);

但我仍然收到相同的 ArticleId 验证错误,然后我签入 Watch,我尝试的所有树方法都返回 False

我也尝试了以下方法:

UpdateModel(articlecomment);

UpdateModel<ArticleComment>(articlecomment);

以上方法正在生成异常:

“Outliner.Models.ArticleComment”类型的模型不能 更新了。

这是我的模型:

 [Table("ArticleComments")]
    public class ArticleComment
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

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

        public string UserId { get; set; }

        [Required]
        [Display(Name = "Comment")]
        public string Comment { get; set; }

        [Required]
        [Display(Name = "Commented On")]
        public DateTime CommentDate { get; set; }

    }

我不明白,为什么我的模型没有更新... :(

【问题讨论】:

  • 你能显示你的路线吗?只有在表单中的 HTML 才会发布到服务器。
  • 我已经更新了我的问题并为我的部分视图添加了代码。

标签: c# asp.net-mvc-4 razor


【解决方案1】:

这是一个很晚的答案,但它应该工作。

ModelState.IsValid之前,添加关注

ModelState.Remove("ArticleId");

它将从验证中删除该字段。

【讨论】:

    【解决方案2】:

    您可以在检查ModelState.IsValid 之前尝试一次TryUpdateModel(articlecomment)。但是我没有测试过

    【讨论】:

    • TryUpdateModel 是一个泛型方法
    • 我签入了 Watch ... TryUpdateModel 返回错误。请看更新
    【解决方案3】:

    在 ModelBind 之后更新任何 requerid 字段后,您必须调用另一个方法来更新验证。

    你可以使用:

    TryValidateModel(articlecomment);
    

    TryUpdateModel<ArticleComment>(articlecomment);
    

    【讨论】:

    • 仍然得到“The ArticleId field is required” :(
    • 我签入了手表..两种方法都返回错误...,请参阅更新
    【解决方案4】:

    对我来说,您的@Html.Action(...) 代码似乎调用了创建局部视图的操作,就像您说的那样。如果您这样做,则不是调用局部视图的正确方法。虽然返回部分视图的操作并不少见,但根据我的经验,它通常是通过 AJAX 进行的,因此您可以在它返回后将其插入 DOM。

    您可以使用以下方法来渲染局部视图:

    @{ 
        Html.RenderPartial("_myPartialView", 
                           new ArticleComment {ArticleId = model.Id}); 
    }
    

    这应该渲染您的局部视图,将您的模型传递给它,以便它可以正确渲染。然后,当表单被 POST 到服务器时,它应该从表单数据创建模型。您不需要 AID 参数,因为它是您的 ArticleComment 模型的一部分。

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 1970-01-01
      • 2022-09-25
      • 2019-05-27
      • 2017-04-14
      • 2020-06-09
      • 1970-01-01
      • 2011-08-02
      • 2019-05-20
      相关资源
      最近更新 更多