3

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.

2 Answers 2

8

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

});
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, but how do you make sure this bit of code is always inserted in the view when there's a Material.Serial field in the model?
5

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="" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.