試試這個: 先改變你的ID名myfeild這樣的:
@Html.TextBoxFor(model => item.myfeild, new { placeholder = "Required", @class = "myclass", require = "true", maxlength = "1", id = "myfeild" })
然後使用以下腳本:
<script type="text/javascript">
$(document).ready(function() {
if ($("#myfeild").val() == "") {
$("#myfeild").val('0');
}
$("#myfeild").keydown(function (event) {
if ($("#myfeild").val() == "0") {
$("#myfeild").val('');
}
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
$("#myfeild").keyup(function (event) {
if ($("#myfeild").val() == "") {
$("#myfeild").val('0');
}
});
});
</script>
如果你的視圖中有你的屬性的數據類型爲「int」,那麼它應該自動爲你做。 –