Skip to main content
 首页 » 编程设计

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

2024年02月05日1052php

我有一个使用数据脚手架生成的 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 中访问模型。