如何将隐藏字段值从视图传递到控制器ASP.NET MVC 5

问题描述 投票:5回答:4

我试图通过执行以下操作将隐藏的字段值从视图传递到控制器

@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; }
}
c# asp.net-mvc entity-framework
4个回答
5
投票

视图中的模型是ArticlesCommentsViewModel,因此POST方法中的参数必须匹配。你的用途

@Html.HiddenFor(model => model.Articles.ArticleId)

是正确的,但您需要将方法更改为

[HttpPost]
public ActionResult Create(ArticlesCommentsViewModel model)

并且模型将被正确绑定。

作为旁注,您的ArticlesCommentsViewModel不应包含数据模型,而应仅包含视图中所需的那些属性。如果typeof Articles包含具有验证属性的属性,则ModelState将无效,因为您未发布Article的所有属性。

但是,由于CommentsViewModel已经包含ArticleId的属性,那么你可以使用

@Html.HiddenFor(model => model.Comments.ArticleId)

并在POST方法中

[HttpPost]
public ActionResult Create([Bind(Prefix="Comments")]CommentsViewModel model)

有效地剥离“评论”前缀


1
投票

在控制器中,您需要使用模型传递隐藏值,例如,如果您有一个userId作为隐藏值,则在您添加的页面中: @Html.HiddenFor(x => x.UserId)

在您的模型中,您当然也有UserId。 在控制器中,您需要将模型作为参数。 public async Task<ActionResult> ControllerMethod(YourViewmodel model) { model.UserId //this should be your HiddenValue


1
投票

我想你的模型在Articles中有另一个名为CommentsViewModel的类。更改你的控制器函数以相应地访问ArticleId。

[HttpPost]
public ActionResult Create(CommentsViewModel comments)//, int ArticleId)
{
    var comment = new Comments
    {
        Comment = Server.HtmlEncode(comments.Comment),
        ArticleId = comments.Articles.ArticleId,  // Since you are using model.Articles.ArticleId in view
        CommentByUserId = User.Identity.GetUserId()
    };
}

0
投票

就我而言,我在控制器和视图之间来回传递了几个字段。所以我在视图中使用了隐藏字段。这是视图的一部分。请注意,控制器已在ViewBag中设置“selectedTraining”和“selectedTrainingType”以传递给视图。所以我希望这些值可以传递给控制器​​。在隐藏标记上,关键的东西设置为“name”属性。 “id”不会为你做。

@using (Html.BeginForm("Index", "ComplianceDashboard"))
{

<input type="hidden" value="@ViewBag.selectedTraining" id="selectedTraining" name="selectedTraining" />
<input type="hidden" value="@ViewBag.selectedTrainingType" id="selectedTrainingType" name="selectedTrainingType" />

if (System.Web.HttpContext.Current.Session["Dashboard"] != null)
{
    // Show Export to Excel button only if there are search results
    <input type="submit" id="toexcel" name="btnExcel" value="Export To Excel" class="fright" />
}

<div id="mainDiv" class="table">
    @Html.Grid(Model).Columns(columns =>

然后回到控制器上:

        // POST: Dashboard (Index)
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(string excel)
        {
            string selectedTraining, selectedTrainingType;

            selectedTraining = Request["selectedTraining"];
            selectedTrainingType = Request["selectedTrainingType"];

或者可以将请求作为参数放到方法中:public ActionResult Index(string excel,string selectedTraining,string selectedTrainingType)

© www.soinside.com 2019 - 2024. All rights reserved.