gpt4 book ai didi

c# - 在 MVC 中将值从 Controller 传递到 View

转载 作者:太空宇宙 更新时间:2023-11-03 21:17:45 24 4
gpt4 key购买 nike

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

创建 View :

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

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

Controller :

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

最佳答案

您可以通过使用 ViewBag 来存储 GroupId 来实现这一点,但由于您的 View 使用的是模型,因此最好采用这种方式相反。

所以你会:

型号:

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

Controller :

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

return View(model);
}

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

@model GroupModel

然后,您可以根据脚手架完成的情况,使用 model.GroupId 之类的代码在 View 中访问模型。

关于c# - 在 MVC 中将值从 Controller 传递到 View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com