MVC 2 TextBoxFor 在视图之外不起作用
我想通过编写一个方法来生成字段名称、输入框和任何验证消息的 HTML,从而从“编辑”视图表单中删除重复的代码。这是系统生成的默认视图代码的示例:
<div class="editor-label">
<%: Html.LabelFor(model => model.dateAdded) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.dateAdded, String.Format("{0:g}", Model.dateAdded)) %>
<%: Html.ValidationMessageFor(model => model.dateAdded) %>
</div>
这是我开始编写的内容:
MvcHtmlString DataField(HtmlHelper h, Object m)
{
string s=h.TextBoxFor(m => m.dateAdded);
}
现在我知道这不会正常工作,这只是一个开始,但我收到错误“'System.Web.Mvc” .HtmlHelper'不包含'TextBoxFor'的定义,并且找不到接受'System.Web.Mvc.HtmlHelper'类型的第一个参数的扩展方法'TextBoxFor'”。
I wanted to remove repeated code from my 'edit' view forms by writing a method to generate the HTML for the field name, input box, and any validation messages. Here is an example of the default view code generated by the system:
<div class="editor-label">
<%: Html.LabelFor(model => model.dateAdded) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.dateAdded, String.Format("{0:g}", Model.dateAdded)) %>
<%: Html.ValidationMessageFor(model => model.dateAdded) %>
</div>
And here is what I started to write:
MvcHtmlString DataField(HtmlHelper h, Object m)
{
string s=h.TextBoxFor(m => m.dateAdded);
}
Now I know that won't work properly, it's just a start, but I get the error "'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否正在尝试编写一个自定义 HTML 帮助程序来生成此 HTML?我建议您使用自定义编辑器模板,因为您拥有的是主要标记。因此,您可以拥有以下部分 (
~/Views/Shared/EditorTemplates/SomeViewModel.ascx
):然后每当您有 SomeViewModel 的强类型视图时:
或者如果您有 SomeViewModel 类型的属性:
这将呈现自定义编辑器模板。
就帮助者而言,正确的签名是:
Are you trying to write a custom HTML helper that would generate this HTML? I would recommend you using a custom editor template because what you have is primary markup. So you could have the following partial (
~/Views/Shared/EditorTemplates/SomeViewModel.ascx
):and then whenever you have a strongly typed view to SomeViewModel simply:
or if you have a property of type SomeViewModel:
which would render the custom editor template.
As far as the helper is concerned the proper signature would be: