【问题标题】:How can I pass hidden field value from view to controller ASP.NET MVC 5?如何将隐藏字段值从视图传递到控制器 ASP.NET MVC 5?
【发布时间】: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


【解决方案1】:

视图中的模型是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)

有效去除“评论”前缀

【讨论】:

  • "附带说明,您的 ArticlesCommentsViewModel 不应包含数据模型,而应仅包含您在视图中需要的那些属性。如果 typeof Articles 包含具有验证属性的属性,则 ModelState 将无效,因为您的没有发布文章的所有属性。”实现了这一点并按预期工作,感谢斯蒂芬
【解决方案2】:

在您的控制器中,您需要将隐藏值与模型一起传递, 例如,如果您有一个 userId 作为隐藏值,请在您的页面中添加:
@Html.HiddenFor(x =&gt; x.UserId)

当然,在您的模型中,您也已经拥有 UserId。
在您的控制器中,您需要模型作为参数。
public async Task&lt;ActionResult&gt; ControllerMethod(YourViewmodel model) { model.UserId //this should be your HiddenValue

【讨论】:

    【解决方案3】:

    我猜您的模型在CommentsViewModel 内还有另一个名为Articles 的类。相应地更改您的控制器函数以访问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()
        };
    }
    

    【讨论】:

    • 而且您可能需要确保可以创建和创建 Articles 对象...
    【解决方案4】:

    在我的例子中,我在控制器和视图之间来回传递了几个字段。所以我利用了视图中的隐藏字段。 这是视图的一部分。请注意,控制器在 ViewBag 中设置了“selectedTraining”和“selectedTrainingType”以传递给视图。所以我希望这些值可以传递给控制器​​。在隐藏标签上,关键的东西被设置为“名称”属性。 “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)

    【讨论】:

      【解决方案5】:

      在我的例子中,我没有将hidden 输入放在表单部分,但它不在表单中,所以它不会发送到后端。确保在表单中输入hidden

      【讨论】:

        【解决方案6】:

        还要确保在隐藏字段上指定名称属性。元素的“id”经常用在客户端,而“name”用在服务器端。

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

        【讨论】:

          猜你喜欢
          • 2016-05-28
          • 1970-01-01
          • 1970-01-01
          • 2016-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多