问题
How can I add to ALL textboxes in ALL aspx sites, like:
<%: Html.TextBoxFor(model => model.Firstname, new { style = "float: left; width: 4.1em;", maxlength = "4" })%>
a javascript function without searching them and adding manually something like:
new { onkeyup='Foo(this); return false;' }
Idea: Writing an ascx
like the following one!
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%: Html.TextBox( string.Empty,
ViewData.TemplateInfo.FormattedModelValue,
new { onkeyup = "foo(this); return false;" })%>
Please let us say this ascx
is named Test.ascx
and that it is stored in \Views\Shared\EditorTemplates\
.
My problem is that "Test.ascx" isnt called.
Why?
Must a reference be added to all aspx sites?
Is there a < System.String>
in the Inherit missing?
Any help would be fine.
Thank you very much in advance.
回答1:
In order for your custom editor template to be called you need to use:
<%= Html.EditorFor(model => model.Firstname) %>
and not:
<%= Html.TextBoxFor(model => model.Firstname, new { style = "float: left; width: 4.1em;", maxlength = "4" })%>
By using Html.TextBoxFor you are explicitly hardcoding this value and that you want an <input type="text" ...
and you cannot override or replace it. That's the reason why it is good practice to use Html.EditorFor
as it allows you to modify the way this is rendered by defining a custom template in the Views\Shared\EditorTemplates
folder.
Now if you editor template is called: Test.ascx
you could invoke it like this:
<%= Html.EditorFor(model => model.Firstname, "Test") %>
or by decorating your view model property with the [UIHint] attribute:
[UIHint("Test")]
public string Firstname { get; set; }
and then simply:
<%= Html.EditorFor(model => model.Firstname) %>
来源:https://stackoverflow.com/questions/5126696/how-to-overwriting-all-html-textbox-ascx-not-called-why