【发布时间】:2017-01-17 05:56:36
【问题描述】:
我正在尝试通过执行以下操作将隐藏字段值从视图传递到控制器
@Html.HiddenFor(model => model.Articles.ArticleId)
也试过了
<input type="hidden" id="ArticleId" name="ArticleId" value="@Model.Articles.ArticleId" />
在这两种情况下,ArticleId 的值都是 0,但是当我使用 TextboxFor 时,我可以看到正确的 ArticleId,请帮助
这里是
查看
@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这是一个收藏? -
不,不是收藏
-
在两个实例中,ArticleId 的值都是 0 是什么意思?
-
你可以调试你的代码...
-
由于您的视图使用
Articles.ArticleId但在您的 POST 方法中您尝试使用comments.ArticleId访问它,您显然在视图中有不同的模型。它是什么? (视图中的模型需要是CommentsViewModel,或者如果它的模型包含CommentsViewModel的属性,那么您需要一个带有Prefix属性的BindAttribute)
标签: c# asp.net-mvc entity-framework