user3543878 user3543878 - 3 months ago 38
C# Question

How can i pass hidden field value from view to controller ASP.NET MVC 5

I am trying to pass hidden field value from view to controller by doing the following

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


and also tried

<input type="hidden" id="ArticleId" name="ArticleId" value="@Model.Articles.ArticleId" />


On both instances the value of ArticleId is 0 but when i use TextboxFor i can see the correct ArticleId, please help

Here it is

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>
}


Controller

// 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()
};
}


Model

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; }
}


ViewModel

public class ArticlesCommentsViewModel
{
public Articles Articles { get; set; }
public CommentsViewModel Comments { get; set; }
}

Answer

The model in the view is ArticlesCommentsViewModel so therefore the parameter in your POST method must match. Your use of

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

is correct, but you need to change the method to

[HttpPost]
public ActionResult Create(ArticlesCommentsViewModel model)

and the model will be correctly bound.

As a side note, your ArticlesCommentsViewModel should not contain data models, and instead should contain only those properties you need in the view. If typeof Articles contains properties with validation attributes, ModelState would be invalid because your not posting all properties of Article.

However, since CommentsViewModel already contains a property for ArticleId, then you could just use

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

and in the POST method

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

to effectively strip the "Comments" prefix