Html属性打破编辑器模板,将其呈现为只读

时间:2012-03-07 12:39:41

标签: asp.net-mvc-3 mvc-editor-templates

我目前正在开发一个ASP.NET MVC 3项目。我制作了一个自定义编辑器模板来显示百分比。这是我到目前为止的代码。

public class MyClass
{
   // The datatype can be decimal or double
   [Percentage]
   public double MyPercentage { get; set; }
}

[Percentage]属性是一个正常的UI Hint属性,它使用以下代码:

    @model Object
    @{
        string fieldName = ViewData.TemplateInfo.HtmlFieldPrefix;
    }

    <div style="height: 24px;">
        <div style="float: left;">
          @Html.TextBox("", String.Format("{0:0.00}", Model), new
          {
              id = "txt" + fieldName,
              @Class = "magnaNumericTextBox",
              type = "magnaNumericType",
              style = "width:230px"
          })
          &nbsp;%
        </div>
        <div style="float: left;">
            <ul style="height: 24px; list-style: none; padding: 0px; margin: 0px; line-height: none;">
                <li style="line-height: normal"><a id="btn@(fieldName)Up" class="magnaNumericButton button small">
                    ˄</a> </li>
                <li style="line-height: normal"><a id="btn@(fieldName)Down" class="magnaNumericButton button small">
                    ˅</a> </li>
            </ul>
        </div>
    </div>
    <script type="text/javascript">

        $("#btn@(fieldName)Up").click(function ()
        {
            ChangeNumericUpDownValue($('#txt@(fieldName)'), 1);
            return false;
        });

        $("#btn@(fieldName)Down").click(function ()
        {
            ChangeNumericUpDownValue($('#txt@(fieldName)'), -1);
            return false;
        });

        $('#txt@(fieldName)').keypress(function (e)
        {
            NumericUpDownKeyPress($(this), e);
            return false;
        });

    </script>

此编辑器模板使用数字上滚轮,用户可以在他/她喜欢时使用。用户也可以在不使用数字向上功能的情况下自行键入数字。 javascript功能和一切都很好地工作了一段时间,直到昨天。

现在的问题是编辑器模板中的文本框不允许用户键入他/她自己的值(使其只读 - 虽然渲染的html中没有readonly属性),只能通过数字向上按钮。我已经确定如果我从文本框助手中删除html属性,如下所示:

  @Html.TextBox("", String.Format("{0:0.00}", Model))

用户可以通过在文本框中键入值再次添加该值。这可能是什么?任何帮助或建议将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

发生这种情况的原因是您从您订阅的keypress javascript事件中返回false:

$('#txt@(fieldName)').keypress(function (e) {
    NumericUpDownKeyPress($(this), e);
    return false; // <- here you are blocking all keys
});

这意味着无论用户在文本框中键入哪个键,您都要取消它。当你删除属性时,这就是因为没有你的文本框不再具有正确的id,并且你的jquery选择器与任何元素都不匹配,所以它什么都不做允许用户输入他喜欢的任何东西文本框。因此,如果您想允许他输入,则不应该从.keypress()处理程序返回false。或者至少不系统地 - &gt;例如,如果他键入一个应该是此文本框中唯一允许的字符的数字,则可以返回true。

相关问题