1

我使用这个博客中的代码Autocompletion Textbox in MVC Using jQuery

但我的 jQuery 没有触发。我怀疑它与我的选择器有关。我也在使用 MVC,但我看不出这会使 javascript 有什么不同。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;

namespace UserManager.Controllers
{
    public class UserManagerController : Controller
    {
        //
        // GET: /UserManager/

        public ActionResult Index()
        {
            try
            {
                var data = new UserManager.Models.UserManagerTestEntities();
                return View(data.vw_UserManager_Model_Add_Users.ToList());

            }
            catch (Exception ex)
            {
                return View(ViewBag);
            }

        }

        public ActionResult CreateUser()
        {

            var data = new UserManager.Models.UserManagerTestEntities();
            ViewBag.Message = "Create New User";
            return View();
        }

        public ActionResult LookUpGroupName(string q, int limit)
        {
            //TODO: Map list to autocomplete textbox control
            DAL d = new DAL();
            List<string> groups = d.groups();

            var GroupValue = groups
                .Where(x => x.StartsWith(q))
                .OrderBy(x => x)
                .Take(limit)
                .Select(r => new { group = r });

            // Return the result set as JSON
            return Json(GroupValue, JsonRequestBehavior.AllowGet);
        }
    }
}

@model UserManager.Models.vw_UserManager_Model_Add_Users
@{
    ViewBag.Title = "Create New User";
}
<h2>
    CreateUser</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>New User Details</legend>
        <div class="editor-label">
            @Html.LabelFor(Model => Model.salutation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.salutation)
            @Html.ValidationMessageFor(model => Model.salutation)
        </div>
        <div class="editor-label">
            @Html.LabelFor(Model => Model.firstname)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.firstname)
            @Html.ValidationMessageFor(model => Model.firstname)
        </div>
        <div class="editor-label">
            @Html.LabelFor(Model => Model.lastname)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.lastname)
            @Html.ValidationMessageFor(model => Model.lastname)
        </div>
        <div class="editor-label">
            @Html.LabelFor(Model => Model.password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.password)
            @Html.ValidationMessageFor(model => Model.password)
        </div>
        <div class="editor-label">
            @Html.LabelFor(Model => Model.email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.email)
            @Html.ValidationMessageFor(model => Model.email)
        </div>
        <div class="editor-label">
            @Html.LabelFor(Model => Model.isactive)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.isactive)
            @Html.ValidationMessageFor(model => Model.isactive)
        </div>
        <div class="editor-label">
            @Html.Label("Group Name")
            <!-- GroupName -->
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.group_name)
            @Html.ValidationMessageFor(model => Model.group_name)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
}
<script type="text/javascript">
    $(document).ready(function () {
        $("#group_name").autocomplete('@Url.Action("LookUpGroupName")', 
        {
        dataType: 'json',
        parse: function (data) {
            var rows = new Array();
            alert("before loop");
            for (var i = 0; i < data.length; i++) {
                rows[i] = { data: data[i], value: data[i].group, result: data[i].group }
            }
            return rows;
        },
        formatItem: function (row, i, max) {
            return row.group
        },
        width: 300,
        highlight: false,
        multiple: true,
        multipleseparator: ","
    });
});

</script>

呈现给浏览器的 HTML:

<input name="group_name" class="text-box single-line" id="group_name" type="text" value=""/>

可能是一些简单的东西,我只是看不到它。有任何想法吗?谢谢!

4

3 回答 3

1

我不相信@Html.EditorFor(model => Model.group_name)添加和 ID 到它创建的元素,因此您的选择器将不匹配。您可以像这样添加一个 ID:

@Html.EditorFor(model => Model.group_name, new { ID = "group_name"})

此外,如果您不想使用 jquery 在 ID 上进行选择,最好使用 ID 选择器#group_name,除非您实际上有许多元素的 ID 实际上以group_name所有元素开头,并且您想要选择所有元素一次。

更新

您使用以selector开头的属性input[id^=group_name,并且其中有一个错字。您缺少]选择器中的关闭。即便如此,如果您不打算选择多个 ID 都以 开头的元素,那么group_name您的标记表明您没有。那么你应该真正使用 ID 选择器。

于 2012-11-01T15:24:45.430 回答
0

使用 MVC3 Razor 时,此语法将不起作用:

$("#postTags").autocomplete('<%=Url.Action("LookUpGroupName",) %>', 

这是因为 Razor 引擎不理解 WebForms 引擎语法。相反,我使用了:

$("#group_name").autocomplete('@Url.Action("LookUpGroupName")',

我使用了只接受 ActionResult 名称的重载方法。这对我有用,但如果您的解决方案设置不同,您可能必须同时提供 Controller 和 ActionResult 争论。

最后,当我发出 AJAX 请求时,我收到了错误代码 500。这是因为在我的 LookUpGroupName 方法中,我必须重构这行代码:

return Json(GroupValue);

至:

return Json(GroupValue, JsonRequestBehavior.AllowGet);

我原来的帖子有所有正确的代码供任何人将来参考。

于 2012-11-02T09:14:55.400 回答
0

用这个做一个测试运行

 $(function() {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "Scala",
            "Scheme"
        ];
        $( "#group_name" ).autocomplete({
            source: availableTags
        });
    });
于 2012-11-01T15:48:18.870 回答