部分视图上的Jquery AutoComplete结果

时间:2012-11-20 04:47:47

标签: asp.net-mvc jquery-ui

是否可以在局部视图上显示Jquery自动完成的结果? 这就是我现在展示的方式,我希望在局部视图上显示结果,这样我就可以更好地控制结果的样式。

 $(document).ready(function () {
        $('*[data-autocomplete-url]')
            .each(function () {
                $(this).autocomplete({
                    source: $(this).data("autocomplete-url"),
                    minLength: 2,
                    messages: {
                        noResults: "",
                        results: function () { }
                    },
                    select: function (event, ui) {
                        return false;
                    },
                });
            }).data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                    .data("item.autocomplete", item)
                  )
.append('<table><tr><td valign="top"><img style="width:30px;height:30px;" src="' + "/Images/Image.jpg" + '" /></td><td valign="top">' + item.FirstName + item.LastName + '</td></tr></table>')
                                       .appendTo(ul);
            }
    });

此外,当用户从结果中选择一个项目时,我想通过传递id来调用控制器操作,是否有人可以为此提供代码示例?

我使用的是Asp.net MVC 4,

谢谢!

1 个答案:

答案 0 :(得分:1)

您不能仅使用jQuery渲染局部视图。但是,您可以调用一个方法(操作)来为您呈现局部视图,并使用jQuery / AJAX将其添加到页面中。 当用户选择项目或悬停项目时,只需使用jquery函数并使用ajax将id传递给服务器并返回Partail View。

$.get( '<%= Url.Action("details","user", new { id = Model.ID } %>', function(data) {
    $('#detailsDiv').replaceWith(data);
});

剃刀

$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
    $('#detailsDiv').replaceWith(data);
}); 

其中用户控制器具有名为details的详细信息:

public ActionResult Details( int id )
{
    var model = ...get user from db using id...

    return Partial( "UserDetails", model );
}

参考这些链接,您将获得更好的主意。 Render Partial View Using jQuery in ASP.NET MVChttp://www.codeproject.com/Articles/41828/JQuery-AJAX-with-ASP-NET-MVCASP.NET MVC AJAX with jQuery

感谢。希望这会对你有所帮助。