javascript - MVC .NET 将带有 Jquery 自动完成功能的 ViewBag 字符串 [] 数组传递给服务器 ActionResult

标签 javascript jquery arrays asp.net-mvc-4 jquery-autocomplete

我正在尝试通过 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:

http://jsfiddle.net/hutchonoid/wQXJJ/

关于javascript - MVC .NET 将带有 Jquery 自动完成功能的 ViewBag 字符串 [] 数组传递给服务器 ActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21100630/

相关文章:

javascript - 使用中的属性(property)未更新

javascript - 当我打开滑出式菜单时覆盖

jquery - AngularJs:如何将表格滚动到当前的 ng-init 日期?

c - C 中的随机移动 tic tac toe

c - 在我的函数中出现错误,该函数使用 C 中的指针返回数组中的值

ios - 使用 EasyMapping (Swift) 解析 Json 数组

javascript - knockout 将 observableArray 项目向下移动

javascript - nodejs模块中的全局对象是什么?

javascript - 使用 JavaScript 更改列表样式的 onclick

javascript - 如何使用 Modal Bootstrap 确认删除是/否?