在mvc中回发后,自动完成功能无效

时间:2014-02-04 05:58:12

标签: javascript jquery asp.net-mvc autocomplete

在我的mvc应用程序中,我将jquery自动完成添加到搜索框中。我的问题是第一次自动完成工作正常。它会在我们输入搜索框时显示相关项目。选择其中一个项目后,它将重定向到另一个页面。搜索框自动完成功能无效的地方。 这是我的代码:

查看:

<div id="targetDiv">
@Html.TextBox("name", null, new { id = "SearchBox", @class = "SearchBox" })
</div>

Javascript代码:

<script type="text/javascript">
function load() {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(getItems);
}
$(document).ready(function () {

    //We have used keyup event to track the user enter value in the textbox.
    $("#SearchBox").keyup(function () {
        //Fetching the textbox value.
        var query = $(this).val();
        //Calling GetItems method.
        getItems(query);
    });

    function getItems(query) {
        //var path = '@Url.Action("Suggest", "Home")';
        //Here we are using ajax get method to fetch data from the list based on the user entered value in the textbox.
        //We are sending query i.e textbox as data.
        $.ajax({
            url: '@Url.Action( "RemoteData", "Home")',
            data: { "query": query },
            type: 'POST',
            dataType: 'json',
            success: function (response) {
                if (response.Data != null) {
                    if ($("#targetUL") != undefined) {
                        //If the UL element is not null or undefined we are clearing it, so that the result is appended in new UL every next time.
                        $("#targetUL").remove();
                    }
                    //assigning json response data to local variable. It is basically list of values.
                    data = response.Data;
                    //appending an UL element to show the values.
                    $("#targetDiv").append($("<ul id='targetUL'></ul>"));
                    //Removing previously added li elements to the list.
                    $("#targetUL").find("li").remove();
                    //We are iterating over the list returned by the json and for each element we are creating a li element and appending the li element to ul element.
                    $.each(data, function (i, value) {
                        //On click of li element we are calling a method.
                        $("#targetUL").append($("<li class='targetLI' onclick='javascript:appendTextToTextBox(this)'>" + value + "</li>"));

                    });
                }
                else {
                    //If data is null the we are removing the li and ul elements.
                    $("#targetUL").find("li").remove();
                    $("#targetUL").remove();
                }
            },
            error: function (xhr, status, error) {
            }
        });
    }
});

//This method appends the text oc clicked li element to textbox.
function appendTextToTextBox(e) {
    //Getting the text of selected li element.
    var textToappend = e.innerText;
    //setting the value attribute of textbox with selected li element.
    $("#SearchBox").val(textToappend);
    //Removing the ul element once selected element is set to textbox.
    $("#targetUL").remove();
}
</script>

控制器代码:

[HttpPost]
    public ActionResult RemoteData(string query)
    {
        ArrayList list = new ArrayList();
        SearchModel searchmodel = new SearchModel();
        DataTable dt = new DataTable();
        dt = searchmodel.FilteredSearchProductDisplay(query, 5, 0);
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(dr["ProductName"]);
            }
        }

        return Json(new { Data = list });
    }

重定向页:

if (@Model.dtProduct.Rows.Count > 0)
{
    <div style="width:100%; height:auto;">@Html.Raw(@Model.dtProduct.Rows[0]["ThumbnailFilename"])</div>
    <br />
        if (ViewBag.RedirectedFromPage == "Search" || ViewBag.RedirectedFromPage == "OfferProduct")
        {
            if (@Model.dtProduct.Rows[0]["Stock"].ToString().Length > 0)
            {  
                <table id ="priceTable">
                <tr>
                @if(@offerPrice > 0)
                {
                    <td style="width:10%" class="divSizehPrice"><label>@Html.Raw(@Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])@APrice.ToString("0.00")</label></td>
                    <td style="width:90%" class="divSizehPrice"><label>RRP&nbsp;</label><p>@Html.Raw(@Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])@Price.ToString("0.00")</p></td>
                }
                else
                {
                    <td colspan=2 style="width:90%" class="divSizehPrice"><p>@Html.Raw(@Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])@APrice.ToString("0.00")</p></td>
                }                    
                </tr>
                </table>
                <div id="divPrice2"style="display:none">
                    <table>
                    <tr>
                    <td>@Html.Raw(@Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])</td>
                    <td><div id="PriceDiv2"></div></td>
                    </tr>
                    </table>                    
                </div>
                <br />
                <a href="@Url.Action("Currency", "Product", new { ProductId = @Model.dtProduct.Rows[0]["ProductId"], ProductpriceId = @Model.dtProduct.Rows[0]["ProductPriceId"], page = @Model.Page, BrandId = @Model.BrandId, CategoryId = @Model.CategoryId })">Change currency</a>
                <br />
                <a href="@Url.Action("AddToCart", "Cart", new { ProductId = @Model.dtProduct.Rows[0]["ProductId"], ProductpriceId = @Model.dtProduct.Rows[0]["ProductPriceId"], ProductPrice = @APrice })" type="button">Add to Shopping Cart</a>
            }
            else
            {
                using (Html.BeginForm("SelectedProductDisplay", "Product", FormMethod.Post, new { ProductId = @Model.dtProduct.Rows[0]["ProductId"], ProductpriceId = @Model.dtProduct.Rows[0]["ProductPriceId"] }))
                {
                <b>Out of stock</b>
                <br />
                @*<p>Please enter your email address below and we will contact you when it comes back in to stock.</p>
                <br />
                <label>Email:</label> @Html.TextBoxFor(m => m.OutOfStockEmail, new { id = "emailid" })
                <br />
                <div id="erroremail" class="validationColor" style="width:100%; text-align:center"></div>
                <label>@Model.OutOfStockStatus</label>
                <input type="submit" value="Notify Me" onclick="return checkEmail()"/>*@
                }
                <a href="@Url.Action("ContinueShoping", "Product")" type="button" data-theme="f">Continue Shopping</a>
            }
            <br />

            <div class="divSearchHeader">
            <p>@Html.Raw(Model.dtProduct.Rows[0]["ProductName"])</p>
            <br />
            </div>
            <div class="divSearchContent">
            @Html.Raw(@Model.dtProduct.Rows[0]["ProductDescription"])
            </div>
            <div class="divSearchContent">
            @Html.Raw(@Model.dtProduct.Rows[0]["Description"])
            </div>
        }
        else
        {
                <table style="width:100%" id="priceTable1">
                @if (offerPrice > 0)
                {
                    <tr>
                    <td style="width:25%"><div class="divSizehPrice">@APrice.ToString("0.00")</div></td>
                    <td style="width:75%"><div class="divSizehPrice"><p><label>RRP&nbsp;</label>@Price.ToString("0.00")</p></div></td>
                    </tr>
                }
                else
                {
                    <tr>                        
                    <td colspan=2 class="divSizehPrice"><p>@Html.Raw(@Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])@APrice.ToString("0.00")</p></td>
                    </tr>
                }
                </table>
                <div id="divPrice1"style="display:none" class="divSizehPrice">
                    <table>
                    <tr>
                    <td>@Html.Raw(@Model.dtcurrentCurrency.Rows[0]["HTMLENTITY"])</td>
                    <td><div id="PriceDiv1"></div></td>
                    </tr>
                    </table>                    
                </div>

                <br />
                <a href="@Url.Action("Currency", "Product")">Change currency</a>
                <br />
                <a href="@Url.Action("AddToCart", "Cart", new { ProductId = @Model.dtProduct.Rows[0]["ProductId"], ProductpriceId = @Model.dtProduct.Rows[0]["ProductPriceId"], ProductPrice = @APrice })" type="button" data-theme="f">Add to Shopping Cart</a>
                <br />
                <div class="divSearchHeader">
                <p>@Html.Raw(Model.dtProduct.Rows[0]["Name"])</p>
                <br />
                </div>
                <div class="divSearchContent">
                @Html.Raw(@Model.dtProduct.Rows[0]["Description"])
                </div>
        }
}
else
{
    <p>No records found.</p>
}

5 个答案:

答案 0 :(得分:0)

请使用live而不是简单的keyup:

$('selector').live('keyup',function(){

//your code

});

答案 1 :(得分:0)

我还使用了Jquery自动完成搜索框它工作正常,唯一的区别在于控制器代码

public ActionResult Autocomplete(string term)
{
    // Return the Result list store in searchResultList
    return Json(searchResultList, JsonRequestBehavior.AllowGet);    
}
  • 删除了Httpost属性
  • 在返回Json时,使用第二个重载方法JsonRequestBehavior.AllowGet

希望它对您有所帮助,请注意我使用的是MVC4 VS 2010

答案 2 :(得分:0)

尝试:

$('sel').on('keyup',function(){

//your code

});

答案 3 :(得分:0)

请试试这个

$("body").delegate("selector","keyup",function(e){//your code.})

答案 4 :(得分:0)

试试这个:

$('selector').on('input', function(){
// Do your stuff here
});

检查'input'事件,