使用ASP.NET MVC在View的EditorFor()方法中显示ViewBag的值

fuz*_*zzi 4 c# asp.net asp.net-mvc editorfor razor

这可能是我的语法错误,但我无法EditorFor在我的视图中为我设置默认值ViewBag.

我已经检查ViewBag.FirstName过正确传递的值,没关系.但是,该字段显示没有任何价值.

我的发言是:

@Html.EditorFor(model => model.Person.FirstName, new { htmlAttributes = new { @class = "form-control" } ,  @Value = ViewBag.FirstName })
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.
为我的问题简单而道歉.

joh*_*ose 11

你应该以正常方式进行模型绑定:通过赋值模型属性的值.ViewBag是不可维护的,不是强类型的.

如果你真的这样做需要ViewBag出于某种原因,只动分配给@Value你的内部htmlAttributes对象,像这样:

@Html.EditorFor(model => model.Person.FirstName, new { htmlAttributes = new { @class = "form-control", @Value = ViewBag.FirstName } })
Run Code Online (Sandbox Code Playgroud)