在mvc中回发后自动完成功能不起作用
Posted
技术标签:
【中文标题】在mvc中回发后自动完成功能不起作用【英文标题】:Autocomplete is not working after Postback in mvc 【发布时间】:2014-02-27 23:33:09 【问题描述】:在我的 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 </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 </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>
【问题讨论】:
重定向时是否调用$("#SearchBox").keyup函数? @Rakhita 是的,keyup 函数调用工作正常 在浏览器的开发者工具中你能看到发送到 RemoteData 的请求吗?? @ScottSelby 我尝试了所有选项,无法获得解决方案 @Rakhita,@Scott Selby 有时 keyup 功能也不起作用。 【参考方案1】:请使用 live 而不是 simple keyup:
$('selector').live('keyup',function()
//your code
);
【讨论】:
我也试过这个。但在我的 mvc 应用程序中回发后它不起作用。 回发后脚本函数没有调用。【参考方案2】:试试:
$('sel').on('keyup',function()
//你的代码
);
【讨论】:
【参考方案3】:请试试这个
$("body").delegate("selector","keyup",function(e)//your code.)
【讨论】:
用户被删除或与帐户解除关联。所以没有人可以尝试这个来验证。您应该添加一个解释为什么这回答了这个问题,所以这对未来的读者有一些价值。你可以编辑你的答案来做到这一点。【参考方案4】:试试这个:
$('selector').on('input', function()
// Do your stuff here
);
检查“输入”事件,
【讨论】:
【参考方案5】:我还使用了 Jquery AutoComplete Search Box,它工作正常,唯一的区别在于控制器代码
public ActionResult Autocomplete(string term)
// Return the Result list store in searchResultList
return Json(searchResultList, JsonRequestBehavior.AllowGet);
已移除 Httpost 属性
在返回 Json 时,使用第二种重载方法 JsonRequestBehavior.AllowGet
希望对您有所帮助,请注意我使用的是 MVC4 VS 2010
【讨论】:
以上是关于在mvc中回发后自动完成功能不起作用的主要内容,如果未能解决你的问题,请参考以下文章
回发后,我的 JavaScript 函数在 ASP.NET 中不起作用