为什么我的自动完成没有工作MVC3 Razor Engine

时间:2012-11-01 15:20:57

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

我使用此博客中的代码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=""/>

可能是一些简单的事情,我无法看到它。有任何想法吗?谢谢!

3 个答案:

答案 0 :(得分:1)

我不相信@Html.EditorFor(model => Model.group_name)为其创建的元素添加ID和ID,因此您的选择器将不匹配。您可以添加如下ID:

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

此外,如果您不想使用jquery选择ID,最好使用ID选择器#group_name,除非您实际上有许多ID实际上以{{{ 1}}对于所有这些,你想一次选择所有元素。

<强>更新

您使用attribute start with选择器group_name,并在其中输入拼写错误。您错过了选择器中的结束input[id^=group_name。即便如此,如果您不打算选择所有ID都以]开头的多个元素,那么您的标记就表明您没有。那么你应该真的使用ID选择器。

答案 1 :(得分:0)

使用此

进行测试
 $(function() {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "Scala",
            "Scheme"
        ];
        $( "#group_name" ).autocomplete({
            source: availableTags
        });
    });

答案 2 :(得分:0)

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

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

这是因为Razor Engine不了解WebForms Engine语法。相反,我用过:

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

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

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

return Json(GroupValue);

要:

return Json(GroupValue, JsonRequestBehavior.AllowGet);

我的原帖有任何未来参考的正确代码。