user1025852
user1025852

Reputation: 2784

set my model with viewbag value

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

Answers (2)

Jason Evans
Jason Evans

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

Satpal
Satpal

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

Related Questions