将Parmeter传递给来自JQuery Autocomplete插件的ASP.Net MVC2 Action

时间:2011-04-04 17:33:54

标签: jquery asp.net-mvc jquery-autocomplete

我使用以下代码将2个硬编码参数传递给ASP.Net MVC2 Controller Action:

<script type="text/javascript">
    $(document).ready(function () {
        $("form#search_for_entity_user input#term").autocomplete({
            source: '<%= Url.Action("GetEntitySharedUsers", "Search") %>',
            delay: 200,
            minLength: 3,
            select: function (event, ui) {
                $.post('<%= Url.Action("AddSharedUser", "Entity", new { id = "42", snlid="17394" }) %>',
                function (data) { })
            }
        });
    });
</script>

这很好用,但现在我需要更改$ .post中传入的值来自我的模型,所以我想的是类似下面的代码,但这不起作用。关于如何解决这个问题的任何想法?

<script type="text/javascript">
    $(document).ready(function () {
        $("form#search_for_entity_user input#term").autocomplete({
            source: '<%= Url.Action("GetEntitySharedUsers", "Search") %>',
            delay: 200,
            minLength: 3,
            select: function (event, ui) {
                $.post('<%= Url.Action("AddSharedUser", "Entity", new { id = '<%= Model.EntityId  %>', name= '<%= Model.Name  %>' }) %>',
                function (data) { })
            }
        });
    });
</script>

1 个答案:

答案 0 :(得分:3)

这个怎么样?

<script type="text/javascript">
    $(document).ready(function () {
        $("form#search_for_entity_user input#term").autocomplete({
            source: '<%= Url.Action("GetEntitySharedUsers", "Search") %>',
            delay: 200,
            minLength: 3,
            select: function (event, ui) {
                $.post('<%= Url.Action("AddSharedUser", "Entity", new { id = Model.EntityId, name = Model.Name }) %>',
                function (data) { })
            }
        });
    });
</script>

如果是我,我会提取数据,因此它更具语义性:

<input id="term" data-source-url="<%= Url.Action("GetEntitySharedUsers", "Search") %>" data-select-url="<%= Url.Action("AddSharedUser", "Entity", new { id = Model.EntityId, name = Model.Name }) %>" />

<script type="text/javascript">
    $(document).ready(function () {
        var term = $("form#search_for_entity_user input#term");

        term.autocomplete({
            source: term.data('source-url'),
            delay: 200,
            minLength: 3,
            select: function (event, ui) {
                $.post(term.data('select-url'), function (data) { });
            }
        });
    });
</script>