Reputation: 2784
Within a form I populate my output model (that will be handled by the controller). One value is not a user input, it is actually an object from previous page I injected with Viewbag to this page. Now I want to set this object to one of my model properties (complex object) and I'm looking for a way to do it. I encountered
@Html.HiddenFor(m =>
But I can't seem to understand how to set my propery there
Upvotes: 0
Views: 1864
Reputation: 29186
If the property is available in the ViewBag
object, then you could do this.
public ActionResult Index()
{
var viewModel = new YourViewModelClass();
viewModel.Property = ViewBag.Property;
return View(viewModel);
}
[HttpPost]
public ActionResult Index(YourViewModel viewModel)
{
// viewModel.Property will contain the hidden input value.
}
View
@Html.HiddenFor(m => m.Property);
This way, you keep the value from the ViewBag
inside your viewmodel when it is posted back to the server.
Upvotes: 1
Reputation: 133403
As per my understanding, You can not use HiddenFor
without using a model.
You can try,
@Html.Hidden("FieldId", ViewBag.FieldId)
Access it in controller like
public ActionResult Action(string FieldId)
{
//Do something
}
Upvotes: 1