use*_*878 6 c# asp.net-mvc entity-framework
我正在尝试通过执行以下操作将隐藏字段值从视图传递到控制器
@Html.HiddenFor(model => model.Articles.ArticleId)
Run Code Online (Sandbox Code Playgroud)
并尝试了
<input type="hidden" id="ArticleId" name="ArticleId" value="@Model.Articles.ArticleId" />
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,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>
}
Run Code Online (Sandbox Code Playgroud)
控制者
// 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()
};
}
Run Code Online (Sandbox Code Playgroud)
模型
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; }
}
Run Code Online (Sandbox Code Playgroud)
视图模型
public class ArticlesCommentsViewModel
{
public Articles Articles { get; set; }
public CommentsViewModel Comments { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
小智 5
视图中的模型是ArticlesCommentsViewModel如此,因此POST方法中的参数必须匹配。您的使用
@Html.HiddenFor(model => model.Articles.ArticleId)
Run Code Online (Sandbox Code Playgroud)
是正确的,但是您需要将方法更改为
[HttpPost]
public ActionResult Create(ArticlesCommentsViewModel model)
Run Code Online (Sandbox Code Playgroud)
并且模型将被正确绑定。
附带说明,您ArticlesCommentsViewModel不应包含数据模型,而应仅包含视图中所需的那些属性。如果typeof Articles包含具有验证属性的属性,则ModelState该属性将无效,因为您没有发布的所有属性Article。
但是,由于CommentsViewModel已经包含的属性ArticleId,因此您可以使用
@Html.HiddenFor(model => model.Comments.ArticleId)
Run Code Online (Sandbox Code Playgroud)
并在POST方法中
[HttpPost]
public ActionResult Create([Bind(Prefix="Comments")]CommentsViewModel model)
Run Code Online (Sandbox Code Playgroud)
有效地去除“ Comments”前缀
| 归档时间: |
|
| 查看次数: |
31579 次 |
| 最近记录: |