2010-10-04 86 views
2

下面的語句:ASP.NET MVC EditorFor自定義JavaScript

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

生成下面的代碼;

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

我想通過EditorFor語句的onkeypress javascript屬性添加到我的投入,我試圖做到以下幾點:

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

但是,這是行不通的。

回答

8

其難度附加屬性傳遞到EditorFor模板,但或者相同的功能可以使用jQuery或類似的東西來實現:

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

    disableEnterKey(event); 

}); 
+0

好吧,但你如何保證這段代碼總是在視圖中插入時,有在模型中Material.Serial場? – fretje 2011-03-11 10:44:13

2

使用以下....注意代碼的最後一部分。對於產生

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

HTML上方,將會

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