Domanda

I'm trying to pass a string array saved in a ViewBag back to the server ActionResult via jQuery's autocomplete functionality. I'm doing this to try and persist the data so that I don't have to keep retrieving the prices every time I make a call to the server (prices are retrieved through crawling a url). So here is what I have so far:

The Textbox:

 @Html.TextBoxFor(r => r.NewPostModel.NewManualPrice, null, new { @class = "form-control", @type="number", id = "input-post-price", placeholder = "Enter the price" })

The 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);
            }
        });
    })

And the 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);
        }

The code works fine if I replace the source with :

'@Url.Action("PriceSearch", "ModalItem", new { Area = "" } )'

and remove the 'string prices' parameter from the actionresult. But I want to be able to pass the array back as well. Anyone know how to achieve this?

È stato utile?

Soluzione

You have a minor typo, you need to change this:

{ prices: priceTags) }

To this:

{ prices: priceTags }

Removing the extra ) bracket

Here is a jsFiddle with an example of passing the data:

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top