在MVC中将值从Controller传递给View

我有一个使用数据脚手架生成的视图。 该视图有一个文本字段:

创建视图:

@Html.LabelFor(model => model.GroupId, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.GroupId, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.GroupId, "", new { @class = "text-danger" })

我想将控制器中的值传递给此文本字段。 我做了以下,似乎没有用。

控制器:

  public ActionResult Create(int id) { ViewBag.GroupId = id; Debug.WriteLine("DEBUG: "+id); return View(); } 

您可以使用ViewBag来存储GroupId ,但是当您的视图使用模型时,最好采用这种方式。

所以你会:

模型:

 public class GroupModel { public int GroupId { get; set; } } 

控制器:

 public ActionResult Create(int id) { var model = new GroupModel(); model.GroupId = id return View(model); } 

在视图的顶部,您将引用您的模型:

 @model GroupModel 

然后,您可以使用类似model.GroupId代码在视图中访问模型。

还有一点要指出的是,如果要传递存储在web.config文件中的键值,例如reCAPTCHA,并且validation失败,那么您还需要在HttpPost部分中设置键值。