在MVC中将值从Controller传递到View [英] Passing value from Controller to View in MVC
问题描述
我有一个使用数据支架生成的视图.该视图具有文本字段:
I have a view that was generated using data scaffolding. The view has a textfield:
创建视图:
<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.
控制器:
public ActionResult Create(int id)
{
ViewBag.GroupId = id;
Debug.WriteLine("DEBUG: "+id);
return View();
}
推荐答案
您可以通过使用ViewBag
像现在一样存储GroupId
来做到这一点,但是由于视图使用模型,可能会更好往那边走吧.
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.
因此您将拥有:
型号:
public class GroupModel
{
public int GroupId { get; set; }
}
控制器:
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
然后您可以按照脚手架完成的操作,使用类似model.GroupId
的代码在视图中访问模型.
You can then access the model in the view using code like model.GroupId
as per the scaffolding has done.
这篇关于在MVC中将值从Controller传递到View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!