我正在尝试通过以下方式将隐藏字段的值从视图传递到控制器:
在这两个实例中,ArticleId的值都是0,但是当我使用TextboxFor时,我可以看到正确的ArticleId,请帮忙解决。
代码如下:
View
@Html.HiddenFor(model => model.Articles.ArticleId)
同时也尝试了
<input type="hidden" id="ArticleId" name="ArticleId" value="@Model.Articles.ArticleId" />
在这两个实例中,ArticleId的值都是0,但是当我使用TextboxFor时,我可以看到正确的ArticleId,请帮忙解决。
代码如下:
View
@model ArticlesCommentsViewModel
....
@using (Html.BeginForm("Create", "Comments", FormMethod.Post))
{
<div class="row">
<div class="col-xs-10 col-md-10 col-sm-10">
<div class="form-group">
@Html.LabelFor(model => model.Comments.Comment, new { @class = "control-label" })
@Html.TextAreaFor(m => m.Comments.Comment, new { @class = "ckeditor" })
@Html.ValidationMessageFor(m => m.Comments.Comment, null, new { @class = "text-danger"})
</div>
</div>
</div>
<div class="row">
@*@Html.HiddenFor(model => model.Articles.ArticleId)*@
<input type="hidden" id="ArticleId" name="ArticleId" value="@Model.Articles.ArticleId" />
</div>
<div class="row">
<div class="col-xs-4 col-md-4 col-sm-4">
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary" />
</div>
</div>
</div>
}
控制器
// POST: Comments/Create
[HttpPost]
public ActionResult Create(CommentsViewModel comments)//, int ArticleId)
{
var comment = new Comments
{
Comment = Server.HtmlEncode(comments.Comment),
ArticleId = comments.ArticleId,
CommentByUserId = User.Identity.GetUserId()
};
}
模型
public class CommentsViewModel
{
[Required(ErrorMessage = "Comment is required")]
[DataType(DataType.MultilineText)]
[Display(Name = "Comment")]
[AllowHtml]
public string Comment { get; set; }
public int ArticleId { get; set; }
}
视图模型
public class ArticlesCommentsViewModel
{
public Articles Articles { get; set; }
public CommentsViewModel Comments { get; set; }
}
model.Articles
是一个集合吗? - adricadarArticles.ArticleId
,但在您的 POST 方法中,您试图使用comments.ArticleId
访问它,这表明您的视图中有一个不同的模型。那是什么?(视图中的模型需要是CommentsViewModel
,或者如果它是包含CommentsViewModel
属性的模型,则需要使用带有Prefix
属性的BindAttribute
)。 - user3559349