简体   繁体   中英

Merging Razor with Jquery for autocomplete function

im using this guide http://jqueryui.com/autocomplete/#custom-data and what little i know of C# and razor to try autocomplete 3 textboxes whenever one of them is picked.

so if i type in the partno and choose one from the drop down list, item name, desc and ID are populated. and the same if i type in any other field.

i have created a class and put it in a list with the items in

var varItems = new List<Item>();
            varItems = db.Items.Select(tbl => new Item
                    {
                            ID = tbl.ID,
                            Name = tbl.Name,
                            PartNo = tbl.PartNo,
                            Description = tbl.Description
                    }).ToList();

then sent that in a viewbag

ViewBag.Items = var.items;

then in the view

   $( "#Name" ).autocomplete({
        minLength: 0,
        source: @ViewBag.Items,
        focus: function( event, ui ) {
            $( "#Name" ).val( ui.item.label );
            return false;
        },
        select: function( event, ui ) {
            $( "#Name" ).val( ui.item.Name );
            $( "#PartNo" ).val( ui.item.PartNo );
            $( "#Description" ).html( ui.item.Description );
            return false;
        }
    });

but it doesnt like the viewbag being there. im guessing i have to do some sort of loop to produce something like the below?

var projects = [
      {
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png"
      },
      {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png"
      },
      {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png"
      }
    ];

if so how do i loop my list to create the above?

Thanks guys

try this:

source: @Html.Raw(Json.Encode(@ViewBag.Items));

This would encode your Items to json and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM