josethernandezc
josethernandezc

Reputation: 160

ASP.NET MVC EditorFor custom javascript

The following statement:

<%= Html.EditorFor(model => model.Material.Serial) %>

Generates the following code;

<div class="editor-field">  
    <input type="text" value="" name="Material.Serial" id="Material_Serial" class="input-validation-error">  
    <span id="Material_Serial_validationMessage" class="field-validation-error">Debe ingresar un serial</span>  
</div>

I want to add an onkeypress javascript attribute to my input through the EditorFor statement, I have tried to do the following:

<%= Html.EditorFor(model => model.Material.Serial, new{ onkeypress = "return disableEnterKey(event)"})%>

But this doesn't work.

Upvotes: 3

Views: 9869

Answers (2)

gurusviews
gurusviews

Reputation: 51

Use the following .... note the last part in the code.

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control", @onchange="alert('Hello World')" } })

HTML generated for the above will be

<input class="form-control text-box single-line" data-val="true" data-val-length="The field Title must be a string with a maximum length of 255." data-val-length-max="255" data-val-required="The Title field is required." id="Title" name="Title" onchange="alert(&#39;Hello World&#39;)" type="text" value="" />

Upvotes: 5

automagic
automagic

Reputation: 1077

Its difficult to pass Additional attributes to EditorFor templates, but alternatively the same functionality could be implemented using jQuery or something similar:

$('#Material_Serial').keypress(function(event) {

  disableEnterKey(event);

});

Upvotes: 8

Related Questions