Reputation: 293
Shortly my question is this: I have a View - strongly typed to the model task. I have a form in the view that later will pass to the controller. I want to assign a value to task.CreationUserId in the View. The value came to the view using ViewBag but it is not important How do i do it? What is the syntax?
If you want to read the whole story:
I have a view to create a task. The view is strongly typed to the task model. One of the parameters of the task is taskCreationUserID.
First i have a controller that gets as a parameter CurrentuserId
public ActionResult CreateForEdit(int id)
{
ViewBag.AmountsId = new SelectList(db.Amounts1, "Id", "Interval");
ViewBag.TaskStatusesId = new SelectList(db.TaskStatuses, "Id", "Status");
ViewBag.TaskTypesId = new SelectList(db.TaskTypes, "Id", "Type");
ViewBag.CreationUserID = new SelectList(db.Users, "Id", "UserName");
ViewBag.UserId = id;
return View();
}
That calls this view:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Task</legend>
@Html.HiddenFor(model => model.Id)
div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
And so on...
and then i save this task using the controller:
[HttpPost]
public ActionResult CreateForEdit(Task task)
{
if (ModelState.IsValid)
{
task.CreationDate = DateTime.Now;
task.Piority = "p2";
task.TaskStatusesId = 1;
task.CreationUserID = UserId;
db.Tasks.Add(task);
db.SaveChanges();
return RedirectToAction("Index", new { id = UserId });
}
The question is: how i put in the View the value of ViewBag.UserId so it will return to the controller as task.CreationUserID?
Upvotes: 0
Views: 589
Reputation: 1082
I assume there is a UserId property on your Task object or that you can create one.
Don't put it in the ViewBag but instead create a new Task
object in yout HttpGet
method and assign the value of id
to its property: var task = new Task(); task.CreationUserID = id;
Then pass the Task
object to the View en store task.CreationUserID
in a hidden field: @Html.HiddenFor(model => model.CreationUserID)
In the HttpPost
method you will find retrieve it from the task property task.CreationUserID
so you can delete task.CreationUserID = UserId;
from the if statement
Upvotes: 0
Reputation: 1062
Viewbag is just a dynamic object to hold data. there is no state management involved. what ever store in it will loose on postback.
You have to add the UserId in the model and add a hidden field just like model.id
Upvotes: 1
Reputation: 2192
ViewBag is available for one post back request at a time, you can use Session instead of View Bag
Upvotes: 1