0

很快我的问题是: 我有一个视图 - 模型任务的强类型。我在视图中有一个表单,稍后将传递给控制器​​。我想在视图中为 task.CreationUserId 分配一个值。使用 ViewBag 获得视图的价值,但这并不重要我该怎么做?语法是什么?

如果你想阅读整个故事:

我有一个创建任务的视图。视图是任务模型的强类型。任务的参数之一是 taskCreationUserID。

首先我有一个控制器,它作为参数 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();
        } 

这称为这种观点:

@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>

等等...

然后我使用控制器保存这个任务:

[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 });
            }

问题是:我如何将 ViewBag.UserId 的值放入 View 中,以便它将作为 task.CreationUserID 返回到控制器?

4

3 回答 3

1

ViewBag 一次可用于一个回发请求,您可以使用 Session 代替 View Bag

于 2013-01-17T12:19:05.793 回答
1

Viewbag 只是一个保存数据的动态对象。不涉及状态管理。任何存储在其中的内容都会在回发时松动。

您必须在模型中添加 UserId 并添加一个隐藏字段,就像 model.id

于 2013-01-17T12:22:08.190 回答
0

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

于 2013-01-17T12:28:18.950 回答