【问题标题】:Passing value from Controller to View in MVC在 MVC 中将值从控制器传递到视图
【发布时间】:2015-09-29 15:25:05
【问题描述】:

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

创建视图:

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

我想将一个值从控制器传递到此文本字段。我做了以下,这似乎不起作用。

控制器:

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

【问题讨论】:

  • 您的ViewBag 不是您的model,您不能只是互换它们。如果您在视图中检查ViewBag.GroupId,您将获得价值。如果你需要一个模型,你应该将它传递到你的视图中。

标签: c# asp.net-mvc-4 model-view-controller view controller


【解决方案1】:

您可以通过使用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 之类的代码访问视图中的模型,就像脚手架所做的那样。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2012-01-19
      • 2022-01-12
      • 2016-06-08
      相关资源
      最近更新 更多