将数据从Controller传递到View Asp.net MVC3时为空条目

时间:2012-04-02 17:08:29

标签: asp.net asp.net-mvc asp.net-mvc-3

在我的控制器中我传递一个id,将它存储在ViewBag中,然后从视图中访问它并给出一个空条目

这是控制器:

  public ActionResult Create(int referenceID)
    {
       ViewBag.id = referenceID;
       //   ViewBag.type = type;
       // ViewBag.title = title;
        ViewBag.userID = new SelectList(db.UserProfiles, "userID", "firstName");
        return View();
    } 

这就是我从我的视图中访问它的方式

        @{ Model.referenceID = ViewBag.id ; }

当我要去/邀请/创建/ 1 它给我一个空的输入错误。

2 个答案:

答案 0 :(得分:2)

根据您提供的代码,我会说您的模型为空,因为您的操作不会将任何内容传递给视图。您是否尝试过在页面上显示ViewBag.id?

答案 1 :(得分:0)

首先,您需要确保在路由表中为 / Invitation / Create / {id} 配置路由路径...在global.asax中...即。在您的global.asax的RegisterRoutes方法中......确保你有类似......

的东西
  // Invitation/Create
        routes.MapRoute(
            "Create Invitation",
            "Invitation/Create/{id}",
            new { controller = "Invitation", action = "Create", id= 0 }
        );

如果Create方法中的referenceID是可选的......您需要将referenceID的类型更改为int吗? (nullable int)...如下所示

public ActionResult Create(int? referenceID)
{
  // if referenceID is null then you may redirect the user to a view of your choice..
  // then what ever logic you may wanna write...
}

希望这会有所帮助......

<强>更新

您可以尝试将此地图路线代码移动为您的第一张地图路线代码吗?

可能我应该更好地阅读你的问题...在你的Create action方法中你没有将任何模型返回给你的视图......当你说Model.referenceId时......应该有一个模型(包含referenceID)作为属性)从您的创建操作方法返回...在您的案例中缺少