在MVC中将值从控制器传递给视图 [英] Passing value from Controller to View in MVC

查看:31
本文介绍了在MVC中将值从控制器传递给视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

创建视图:

 

@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" })

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

控制器:

 public ActionResult Create(int id){ViewBag.GroupId = id;Debug.WriteLine("调试:"+id);返回视图();}

解决方案

您可以通过使用 ViewBag 来存储当前的 GroupId视图正在使用模型,最好改用这种方式.

所以你会:

型号:

公共类GroupModel{公共 int GroupId { 获取;放;}}

控制器:

public ActionResult 创建(int id){var model = new GroupModel();模型.GroupId = id返回视图(模型);}

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

@model GroupModel

然后,您可以使用像 model.GroupId 这样的代码访问视图中的模型,根据脚手架所做的工作.

I have a view that was generated using data scaffolding. The view has a textfield:

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

I'd like to pass a value from a controller to this textfield. And I did the following, which doesn't seem to work.

Controller:

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

解决方案

You could do this by using the ViewBag to store GroupId as you currently are, but as your view is using a model, it may be better to go that way instead.

So you would have:

Model:

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

Controller:

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

    return View(model);
}

At the top of your view, you would then reference your model:

@model GroupModel

You can then access the model in the view using code like model.GroupId as per the scaffolding has done.

这篇关于在MVC中将值从控制器传递给视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆