Reputation: 2036
I have 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, I'm pretty sure that ViewBag.id holds a number.
any idea?
Upvotes: 4
Views: 29192
Reputation: 303
You can use hidden type input by setting its 'name' attribute as Model variable to get the value to post method.
<input type="hidden" name="extraValue" value="@ViewBag.id"/>
Upvotes: 0
Reputation: 22619
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
}
Upvotes: 6
Reputation: 9881
You are most likely setting the ViewBag value in the action method. Something like:
ViewBag.id = idValue;
You are also passing in a model to the View:
return View(myModel)
I would recommend you set the extraValue
property in the controller, rather than in the view:
myModel = idValue;
return View(myModel);
Upvotes: 0