获取HTML动态输入值ASP.NET

时间:2011-07-01 22:45:39

标签: asp.net html dynamic input

我在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输入字段中获取值?

如何实现这一目标,这让我感到害怕;)

2 个答案:

答案 0 :(得分: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;
   }
}

答案 1 :(得分:0)

这是使用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帮助解决了这个问题