开发者

MVC 2 TextBoxFor doesn't work outside view

开发者 https://www.devze.com 2023-02-15 01:10 出处:网络
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

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">
    <开发者_Go百科;%: 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".


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):

<%@ Control 
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.SomeViewModel>" %>
<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 then whenever you have a strongly typed view to SomeViewModel simply:

<%= Html.EditorForModel() %>

or if you have a property of type SomeViewModel:

<%= Html.EditorFor(x => x.SomePropertyOfTypeSomeViewModel) %>

which would render the custom editor template.

As far as the helper is concerned the proper signature would be:

using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class HtmlExtensions
{
    public static MvcHtmlString DataField(this HtmlHelper<SomeViewModel> htmlHelper)
    {
        return htmlHelper.TextBoxFor(x => x.dateAdded);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号