user2962142 user2962142 - 1 month ago 7
C# Question

How to Assign a value to the Model from a viewBag in the view

i know this is a dumb question but bare with me please im pretty new.

i got a string property in my model called extraValue, and in the view i got a ViewBag with a value, and i want to assign the Value in the viewbag to the Model property (extraValue)

i tried :

@{Model.extraValue = ViewBag.id}


and i got a null value in the extraValue, im pretty sure that ViewBag.id holds a number.

any idea ?

Answer

You cannot get the value from the ViewBag when you post it.

ViewBag is desiged to put some useful data and accessible at rendering view only

If you want to access then you need to preserve in your view using some Hidden Field.

@{Model.extraValue = ViewBag.id}

and

@Html.HiddenFor(m=>m.extraValue).

Now you can able to get the extraValue in the controller, since you posting back with the help of HiddenField

public ActionResult Save(Model model)
{
   var extra=model.extraValue;// this will bring your viewbag id assigned
}
Comments