I have a View where the User can leave a feedback comment in regards to the content video that is playing on the page. Using the following code I am able to manually enter the UserID and ContentID and it saves to the database without problem.
@using (Html.BeginForm("Screencast", "Media", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="six columns">
<div class="row">
<div class="six columns">
@Html.LabelFor(c => c.FeedbackComment.UserID)
@Html.TextBoxFor(c => c.FeedbackComment.UserID)
</div>
<div class="six columns">
@Html.LabelFor(c => c.FeedbackComment.ContentID)
@Html.TextBoxFor(c => c.FeedbackComment.ContentID)
</div>
<div class="row">
<div class="twelve columns">
@Html.LabelFor(c => c.FeedbackComment.FeedbackString)
@Html.TextAreaFor(c => c.FeedbackComment.FeedbackString)
</div>
</div>
</div>
</div>
</div>
<input type="submit" value="Submit button" class="medium button bottom20"/>
}
However, when the user is on the page before the HTTP post I actually have the related variables in my Model called:
Model.User.UserID
Model.SelectedItem.ContentID
I want to pass these in as hidden fields but when I try to do either:
@HtmlHiddenFor(c => c.FeedbackComment.UserID, @Model.User.UserID)
@HtmlHiddenFor(c => c.FeedbackComment.ContentID, @Model.SelectedItem.ContentID)
or
@HtmlHidden("UserID",@Model.User.UserID)
@HtmlHidden("ContentID",@Model.User.UserID)
Then these values are returned null despite the values being populated before the post. I read about a workaround of putting the input tags in manually but when I did this the @Using.HtmlBeginForm was returning an error of not being set to an instance of an object
Can someone please help me to understand how I can pass these values to the same page using the values I have in the model prior to the post.
Given the following view model (partial):
public class YourViewModel
{
public User User { get; set; }
public SelectedItem SelectedItem { get; set; }
}
You can bind the these properties to a hidden form element. When you post back these properties will still contain their values.
@Html.HiddenFor(x => x.User.UserID)
@Html.HiddenFor(x => x.SelectedItem.ContentID)
Your action method:
public ActionResult YourActionMethod(YourViewModel viewModel)
{
// When you debug here you will see that the values are retained
}
I hope this helps.