我正在用 c# MVC4 编码。
在我的 create.cshtml
我有这个代码:
@{
ViewBag.Title = "My wonderful creation";
}
<script type="text/javascript">
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = this.value.match(/\S+/g).length;
if (words > 100)
{
var trimmed = $(this).val().split(/\s+/, 100).join(" ");
$(this).val(trimmed + " ");
}
});
});
</script>
<div class="editor-field">
@Html.TextAreaFor(model => model.mywonderful, new { @id = "word_count" })
@Html.ValidationMessageFor(model => model.mywonderful)
</div>
这不起作用。当我查看源代码时,代码如下所示:
<script type="text/javascript">
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = this.value.match(/\S+/g).length;
if (words > 100)
{
var trimmed = $(this).val().split(/\s+/, 100).join(" ");
$(this).val(trimmed + " ");
}
});
});
</script>
<div class="editor-field">
<textarea id="word_count" name="mywonderful" rows="2" cols="20">
</textarea>
<span class="field-validation-valid" data-valmsg-for="mywonderful" data-valmsg-replace="true"></span>
</div>
<script src="/Scripts/jquery-1.9.1.js"></script>
如何让字数和验证在 c# mvc 中工作。这在 php 中很容易做到,但是 c# mvc 是另一回事。
我最终使用了普通的旧javascript,这样我就可以对几个文本区域使用相同的代码:
<script type="text/javascript">
var maxWords = 100;
function limitLengthInWords(field)
{
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
if (wordCount >= maxWords)
{
field.value = value.match(re);
}
document.getElementById('description_count').innerHTML = maxWords - wordCount;
}
</script>