【问题标题】:Get HTML dynamic input value ASP.NETASP.NET 获取 HTML 动态输入值
【发布时间】:2011-09-27 02:08:48
【问题描述】:

我在 ASP.NET DropDownList 上使用 jQuery 的 AutoComplete,用户可以选择一个值并提交以进入数据库。但他们也必须能够输入一个值,而我似乎无法在后面的代码中访问该值。

这是 jQuery:

(function ($) {
$.widget("ui.combobox", {
    _create: function () {
        var self = this,
                select = this.element.hide(),
                selected = select.children(":selected"),
                value = selected.val() ? selected.text() : "";
        var input = this.input = $("<input id='txtOptValue'>")
                .insertAfter(select)
                .val(value)
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: function (request, response) {
                        var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                        response(select.children("option").map(function () {
                            var text = $(this).text();
                            if (this.value && (!request.term || matcher.test(text)))
                                return {
                                    label: text.replace(
                                        new RegExp(
                                            "(?![^&;]+;)(?!<[^<>]*)(" +
                                            $.ui.autocomplete.escapeRegex(request.term) +
                                            ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                        ), "<strong>$1</strong>"),
                                    value: text,
                                    option: this
                                };
                        }));
                    },
                    select: function (event, ui) {
                        ui.item.option.selected = true;
                        self._trigger("selected", event, {
                            item: ui.item.option
                        });
                    },
                    change: function (event, ui) {
                        if (!ui.item) {
                            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                valid = false;
                            select.children("option").each(function () {
                                if ($(this).text().match(matcher)) {
                                    this.selected = valid = true;
                                    return false;
                                }
                            });
                            if (!valid) {
                                // remove invalid value, as it didn't match anything
                                //$(this).val("");
                               // select.val("");
                               // input.data("autocomplete").term = "";
                                return false;
                            }
                        }
                    }
                })
                .addClass("ui-widget ui-widget-content ui-corner-left");

        input.data("autocomplete")._renderItem = function (ul, item) {
            return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a>" + item.label + "</a>")
                    .appendTo(ul);
        };

        this.button = $("<button type='button'>&nbsp;</button>")
                .attr("tabIndex", -1)
                .attr("title", "Show All Items")
                .insertAfter(input)
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s"
                    },
                    text: false
                })
                .removeClass("ui-corner-all")
                .addClass("ui-corner-right ui-button-icon")
                .click(function () {
                    // close if already visible
                    if (input.autocomplete("widget").is(":visible")) {
                        input.autocomplete("close");
                        return;
                    }

                    // work around a bug (likely same cause as #5265)
                    $(this).blur();

                    // pass empty string as value to search for, displaying all results
                    input.autocomplete("search", "");
                    input.focus();
                });
    },

    destroy: function () {
        this.input.remove();
        this.button.remove();
        this.element.show();
        $.Widget.prototype.destroy.call(this);
    }
});
})(jQuery);

所以这需要我的 DropDownList,隐藏它,创建一个输入字段作为我的选择,还使我能够输入值。这是我的 DropDownList:

            <asp:FormView ID="frmCreateOptionValue" runat="server" DataKeyNames="OptionValueID"
            DataSourceID="OptionSetValues_DS" DefaultMode="Insert" 
            oniteminserting="frmCreateOptionValue_ItemInserting">
            <InsertItemTemplate>
                <table border="0" cellpadding="0" cellspacing="0" id="id-form">
                    <tr>
                        <th>
                            Add Option Set Value:
                        </th>
                        <td>
                            <div class="ui-widget" runat="server" id="addOptValue">
                                <asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
                                    DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
                                    SelectedValue='<%# Bind("OptionValueID") %>'>
                                    <asp:ListItem Value="" Text="Select One..." />
                                </asp:DropDownList>
                                &nbsp;
                                <asp:ObjectDataSource ID="OptionValues_DS" runat="server" OldValuesParameterFormatString="original_{0}"
                                    SelectMethod="GetDataBy1" TypeName="PurekbbDataSetTableAdapters.tblOptionValueTableAdapter">
                                    <SelectParameters>
                                        <asp:QueryStringParameter Name="oID" QueryStringField="optionSetID" Type="Int32" />
                                    </SelectParameters>
                                </asp:ObjectDataSource>
                            </div>
                        </td>
                        <td>
                            <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
                                CssClass="form-submit" />
                        </td>
                    </tr>
                </table>
            </InsertItemTemplate>
        </asp:FormView>

当用户插入一个项目时:

protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
    // if the value doesn't already exist, create it
    if (e.InputParameters["OptionValueID"] == null)
    {
        // !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
        string ovName = ((TextBox)frmCreateOptionValue.FindControl("txtOptValue")).Text;
        int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);

        tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
        int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));


        e.InputParameters["OptionValueID"] = ovID;
    }
}

我卡在哪里了,如何从 jQuery 中生成的 HTML 输入字段中获取值?

这怎么可能实现,这让我很生气;)

【问题讨论】:

  • 检查我的答案stackoverflow.com/questions/6249549/… 你可以使用相同的方法来做到这一点。
  • 看起来很有希望,我会在哪里做呢?
  • 哎呀!!非常感谢@Miroprocessor ..我在输入中添加了一个 onblur 并将值复制到一个 HiddenField 正如你所说的那样,很有魅力:)
  • 我会添加这个作为答案,但是呃......声誉低于 100 的用户在询问后 8 小时内无法回答自己的问题。奇怪,但我不制定规则!
  • @Leigh:这条规则的想法是新用户不能发布应该是他们问题的编辑的答案。定期参加论坛需要一点时间来适应这种差异。

标签: asp.net html dynamic input


【解决方案1】:

您可以使用 javascript 获取此文本框的值并将其保存在隐藏字段中,然后从后面的代码中读取隐藏字段值

把这个放到javascript里面

$('#HiddenFieldID').val($('#txtOptValue').val());

那么后面的代码会是这样的

protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
    // if the value doesn't already exist, create it
   if (e.InputParameters["OptionValueID"] == null)
   {
       // !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
      string ovName = ((HiddenField)frmCreateOptionValue.FindControl("HiddenFieldID")).Value;
      int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);

      tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
      int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));


      e.InputParameters["OptionValueID"] = ovID;
   }
}

【讨论】:

  • 感谢您的帮助@Miroprocessor,我还发布了完整的解决方案,但将您的标记为答案。现货:)
【解决方案2】:

这是解决这个问题的方法,使用 HiddenField:

将 onblur 添加到动态创建的输入中:

(function ($) {
$.widget("ui.combobox", {
    _create: function () {
        var self = this,
                select = this.element.hide(),
                selected = select.children(":selected"),
                value = selected.val() ? selected.text() : "";
        var input = this.input = $("<input id='txtOptValue' onblur='JavaScript:copyValue()'>") ....

在页面中添加 HiddenField 和 jQuery:

    <asp:HiddenField runat="server" ID="hfoValue" EnableViewState="true" ClientIDMode="Static" />
                            <div class="ui-widget" runat="server" id="addOptValue">
                                <script type="text/javascript" language="javascript">
                                    function copyValue() {
                                        var theVal = $('#txtOptValue').val();
                                        //alert('Copyng ' + theVal);
                                        $('#hfoValue').val(theVal);
                                        //alert('copied');
                                    }
                                </script>
                                <asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
                                    DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
                                    SelectedValue='<%# Bind("OptionValueID") %>'>
                                    <asp:ListItem Value="" Text="Select One..." />
                                </asp:DropDownList> ...

最后访问 HiddenField 中的值:

 protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
    // if the value doesn't already exist, create it
   if (e.InputParameters["OptionValueID"] == null)
   {
       // !!!! FOUND THE VALUE :)
      string ovName = ((HiddenField)frmCreateOptionValue.FindControl("hfoValue")).Value;
      int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);

      tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
      int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));


      e.InputParameters["OptionValueID"] = ovID;
   }
}

感谢@Miroprocessor 帮助解决这个问题

【讨论】:

    猜你喜欢
    • 2015-12-31
    • 2010-09-15
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多