2012-08-31 42 views
0

控制器Asp.Net Mvc JQuery自動完成與多個值?

[HttpGet] 
public JsonResult GetTags() 
{ 
    var data = entity.Tags.Select(x => new { tagName = x.TagName }); 
    return Json(new { result = data }, JsonRequestBehavior.AllowGet); 
} 

SCRIPT

$(function() { 
    function split(val) { 
     return val.split(/,\s*/); 
    } 
    function extractLast(term) { 
     return split(term).pop(); 
    } 
    $("#tags") 
// don't navigate away from the field on tab when selecting an item 
.bind("keydown", function (event) { 
    if (event.keyCode === $.ui.keyCode.TAB && 
    $(this).data("autocomplete").menu.active) { 
    event.preventDefault(); 
     } 
}) 
.autocomplete({ 
    source: function (request, response) { 
    $.getJSON('@Url.Action("GetTags", "Question")', { 
     term: extractLast(request.term) 
}, response); 
}, 
    search: function() { 
     // custom minLength 
    var term = extractLast(this.value); 
    if (term.length < 2) { 
     return false; 
    } 
    }, 
focus: function() { 
    // prevent value inserted on focus 
    return false; 
    }, 
select: function (event, ui) { 
    var terms = split(this.value); 
    // remove the current input 
    terms.pop(); 
    // add the selected item 
    terms.push(ui.item.value); 
    // add placeholder to get the comma-and-space at the end 
    terms.push(""); 
    this.value = terms.join(", "); 
    return false; 
    } 
}); 
}); 

事實上,腳本是從默認jquery-ui-autocomplete-with-multi-values

RAZOR

<div class="demo"> 
    <div class="ui-widget"> 
     @Html.TextBoxFor(x => x.Title, new { @class = "my_text_box", id = "tags" }) 
    </div> 
</div> 

控制器操作被觸發,但我無法在文本框中看到任何數據。我調試的JavaScript,但功能不會觸發。我該如何解決它?

我可以用另一種方式做auto-complete-with-multi-values,不是這樣。

回答

1

你的Action方法正在返回一個Object的集合,它會像這樣構造;

[ { tagName: result1}, {tagName: result2} ... ] 

因爲你直接使用結果爲自動完成,該方法需要在following two formats的一個返回數據;

從本地數據的數據,一個URL或一個回調可以有兩種 變種:

字符串Array:
[ "Choice1", "Choice2" ]

對象與 標籤和值的屬性的數組:
[ { label: "Choice1", value: "value1" }, ... ]

Alt事實上,您可以在將結果發佈到響應方法之前將結果合適地映射到上述格式之一。

+0

當我寫道:'(x => new {label = x.TagName,value = x.TagId})'它仍然不起作用。 –

+0

對不起,它的工作原理。但問題在於它的立場。我的文本框在頁面的下游。但是自動完成的數據顯示在頁面上方。任何想法都沒有? –