我在使用ViewBag和Html.EditorFor时遇到了问题。我正在尝试将名为“ID”的表单字段中的数据从视图“Create.chtml”传递回控制器。我想使用ViewBag。当我尝试按照我在下面的视图中所做的那样做时,它会抛出一个错误 -
Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<dynamic>' has no applicable method named 'EditorFor' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
请让我知道我做错了什么。
控制器:
[HttpPost]
public ActionResult Create(TABLE_CODES dc)
{
try
{
using (var db = new InpEntities())
{
TABLE_CODES codes = new TABLE_CODES(); //TABLE_CODES has data with various columns - ID, NAME, DATE, SOURCE etc.
ViewBag.keys = codes;
db.AddToTABLE_CODES(dc);
db.SaveChanges();
}
return RedirectToAction("Index");
catch
{
return View();
}
}
=======================================================================
View: Create.chtml
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">ID</div>
<div class="editor-field">
@Html.EditorFor(ViewBag.keys.ID) @****** THIS IS NOT WORKING ********@
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
答案 0 :(得分:4)
@Html.EditorFor
需要强类型模型。它不能与ViewBag
。
如果您必须使用ViewBag
将数据传递到视图,请使用@Html.TextFor(...)
代替手动设置输入字段。
但是,我建议您使用强类型模型。
修改强>
型号:
public class MyModel
{
public TABLE_CODES Keys { get; set; }
}
控制器:
var model = new MyModel();
model.Keys = new TABLE_CODES();
return View(model);
查看:
@model MvcApplication1.MyModel
....
@Html.EditorFor(m => m.Keys)