我正在尝试通过 jQuery 的自动完成功能将保存在 ViewBag 中的字符串数组传回服务器 ActionResult。我这样做是为了尝试保留数据,这样我就不必在每次调用服务器时都继续检索价格(价格是通过抓取 url 检索的)。所以这是我到目前为止所拥有的:
文本框:
@Html.TextBoxFor(r => r.NewPostModel.NewManualPrice, null, new { @class = "form-control", @type="number", id = "input-post-price", placeholder = "Enter the price" })
Javascript:
var priceTags = new Array();
var array = @Html.Raw(Json.Encode(@ViewBag.UrlPrices));
for(var i =0; i<array.length;i++){ priceTags[i] = array[i]; }
$(document).ready(function () {
$("#input-post-price").autocomplete({
source: function(request, response) {
$.getJSON('@Url.Action("PriceSearch", "ModalItem", new { Area = "" } )', { prices: priceTags) }, response);
}
});
})
以及 ActionResult:
public ActionResult PriceSearch(string term, string prices)
{
string[] priceList = new string[0];
if (ViewBag.UrlPrices == null)
ViewBag.UrlPrices = priceList;
string[] UrlPrices = ViewBag.UrlPrices;
return this.Json(UrlPrices.Where( p => p.StartsWith(term)), JsonRequestBehavior.AllowGet);
}
如果我将源代码替换为:
,代码可以正常工作'@Url.Action("PriceSearch", "ModalItem", new { Area = "" } )'
并从操作结果中删除“字符串价格”参数。 但我也希望能够将数组传回。任何人都知道如何实现这一点?
最佳答案
你有一个小错别字,你需要改一下:
{ prices: priceTags) }
对此:
{ prices: priceTags }
删除多余的 ) 括号
这是一个带有传递数据示例的 jsFiddle:
关于javascript - MVC .NET 将带有 Jquery 自动完成功能的 ViewBag 字符串 [] 数组传递给服务器 ActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21100630/