2

我正在用 ASP.NET MVC3 开发一个网站。

实际上,我正在尝试实现一个自动完成控件...实际上,当用户键入两个以上的字母时,我想显示这两个字母对应的用户列表。

两周前,我已经成功做到了,结果如下:

在此处输入图像描述

这是代码:

预订日历.cs

//AutoComplete control that return the name and first name of the partner corresponding to "term"
    public ActionResult Name(string term)
    {
        int id = 0;
        var user = User.Identity.Name;
        int inter = int.Parse(user);
        var managers = from d in db.Managers
                       select d;
        managers = managers.Where(s => s.AffiliationNumber == inter);
        foreach (var manager in managers)
        {
            id = manager.TennisClubID;
        }

        var customers = (from c in db.Customers where (c.Name.Contains(term)) && c.TennisClub.ID == id select c.Name + ";" + c.FirstName).Distinct().Take(10);
        return Json(customers, JsonRequestBehavior.AllowGet);
    }

创建.cshtml

@model TennisOnline.Models.Reservation

@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}


<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"> </script>
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/EditorHookup.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.autocomplete.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/jquery.autocomplete.css")" rel="stylesheet" type="text/css"/>

<script type="text/javascript">
$(document).ready(function () {
    $("#Partner").autocomplete({ source: '@Url.Action("Name", "ReservationCalendar")'  }, { minChars: 2 });
});
</script>

 @using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Reservation</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Date)
    </div>
    <div class="editor-field">
        @Html.DisplayFor(model => model.Date)
        @Html.ValidationMessageFor(model => model.Date)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.StartTime)
    </div>
    <div class="editor-field">
        @Html.DisplayFor(model => model.StartTime)
        @Html.ValidationMessageFor(model => model.StartTime)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Double)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Double)
        @Html.ValidationMessageFor(model => model.Double)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Customer.Name)
    </div>
    <div class="editor-field">
        @Html.DisplayFor(model => model.Customer.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Partner)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Partner)
        @Html.ValidationMessageFor(model => model.Partner)
    </div>

    <div class="editor-label">
        @Html.Label("Numéro du court")
    </div>
    <div class="editor-field">
        @Html.DisplayFor(model => model.TennisCourt.Number)
        @Html.ValidationMessageFor(model => model.TennisCourt.Number)
    </div>


    <p>
        <input type="submit" value="Créer" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Retour à l'index", "Index", new { id = Model.TennisClub.ID })
</div>

jQuery.AutoComplete.js

(function($) {
"use strict";

/**
* jQuery autocomplete plugin
* @param {object|string} options
* @returns (object} jQuery object
*/
$.fn.autocomplete = function(options) {
    var url;
    if (arguments.length > 1) {
        url = options;
        options = arguments[1];
        options.url = url;
    } else if (typeof options === 'string') {
        url = options;
        options = { url: url };
    }
    var opts = $.extend({ }, $.fn.autocomplete.defaults, options);
    return this.each(function() {
        var $this = $(this);
        $this.data('autocompleter', new $.Autocompleter(
            $this,
            $.meta ? $.extend({ }, opts, $this.data()) : opts
        ));
    });
};

/**
* Store default options
* @type {object}
*/
$.fn.autocomplete.defaults = {
    inputClass: 'acInput',
    loadingClass: 'acLoading',
    resultsClass: 'acResults',
    selectClass: 'acSelect',
    queryParamName: 'q',
    limitParamName: 'limit',
    extraParams: { },
    remoteDataType: false,
    lineSeparator: '\n',
    cellSeparator: '|',
    minChars: 2,
    maxItemsToShow: 10,
    delay: 400,
    useCache: true,
    maxCacheLength: 10,
    matchSubset: true,
    matchCase: false,
    matchInside: true,
    mustMatch: false,
    selectFirst: false,
    selectOnly: false,
    showResult: null,
    preventDefaultReturn: true,
    preventDefaultTab: false,
    autoFill: false,
    filterResults: true,
    sortResults: true,
    sortFunction: null,
    onItemSelect: null,
    onNoMatch: null,
    onFinish: null,
    matchStringConverter: null,
    beforeUseConverter: null,
    autoWidth: 'min-width',
    useDelimiter: false,
    delimiterChar: ',',
    delimiterKeyCode: 188,
    processData: null
};

/**
* Sanitize result
* @param {Object} result
* @returns {Object} object with members value (String) and data (Object)
* @private
*/
var sanitizeResult = function(result) {
    var value, data;
    var type = typeof result;
    if (type === 'string') {
        value = result;
        data = { };
    } else if ($.isArray(result)) {
        value = result[0];
        data = result.slice(1);
    } else if (type === 'object') {
        value = result.value;
        data = result.data;
    }
    value = String(value);
    if (typeof data !== 'object') {
        data = { };
    }
    return {
        value: value,
        data: data
    };
};

/**
* Sanitize integer
* @param {mixed} value
* @param {Object} options
* @returns {Number} integer
* @private
*/
var sanitizeInteger = function(value, stdValue, options) {
    var num = parseInt(value, 10);
    options = options || { };
    if (isNaN(num) || (options.min && num < options.min)) {
        num = stdValue;
    }
    return num;
};

/**
* Create partial url for a name/value pair
*/
var makeUrlParam = function(name, value) {
    return [name, encodeURIComponent(value)].join('=');
};

/**
* Build an url
* @param {string} url Base url
* @param {object} [params] Dictionary of parameters
*/
var makeUrl = function(url, params) {
    var urlAppend = [];
    $.each(params, function(index, value) {
        urlAppend.push(makeUrlParam(index, value));
    });
    if (urlAppend.length) {
        url += url.indexOf('?') === -1 ? '?' : '&'; // ERROR HERE !!!
        url += urlAppend.join('&');
    }
    return url;
};

   ....

})(jQuery);

奇怪的是,当我尝试在“ReservationCalendar.cs”中使用几乎“相同”的代码时,我在 Firebug 中收到了这个 JS 错误:url.indexOf is not a function... in my js.file so

而且他从来没有达到我的控制器的方法“名称”......

你能帮我找出我做错了什么吗?提前致谢

4

1 回答 1

0

在某些浏览器中,没有 indexOf 功能(如 IE8),因此您需要在原型中添加它。像这样的东西:

if (!Array.prototype.indexOf) 
{ 
  Array.prototype.indexOf = function(elt /*, from*/) 
  { 
    var len = this.length >>> 0; 

    var from = Number(arguments[1]) || 0; 
    from = (from < 0) 
         ? Math.ceil(from) 
         : Math.floor(from); 
    if (from < 0) 
      from += len; 

    for (; from < len; from++) 
    { 
      if (from in this && 
          this[from] === elt) 
        return from; 
    } 
    return -1; 
  }; 
}
于 2013-10-28T13:48:53.847 回答