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

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

我有一个使用数据脚手架生成的 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/

相关文章:

c# - 如何通过ASP.net运行EXE文件?

c# - Asp.net MVC 4.5 使用 EditorFor、按钮单击将对象添加到 ViewModel 中的列表

c# - MVC4 : Compilation Error The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced

javascript - 将值从 Firebase JS 回调方法 (DAL) 返回到另一个函数( Controller )

c# - 使用反射创建命名空间中所有类的列表并转换为其真实类型

c# - 如何显示 tiff 图像?

c# - 从输入中计算字符时,在输出中获取空格字符

asp.net-mvc - MVC 4 中的 ReportViewer 部分

asp.net-mvc - MVC 是编写 asp.net 应用程序的最佳方式吗?

java - 如何在 Spring 3 中将参数从 View 传递到 Controller