jQuery(点击添加文本框值到列表框)不起作用

时间:2014-01-31 12:48:31

标签: c# javascript jquery asp.net-mvc

我已经问了一个问题here,但这更有意义我猜

我想要实现的目标

我希望有一个表单,用户最多可以有三个文本框,用户将至少有一个文本框,可以填写电子邮件。如果他连接到名为superoffice的服务,将显示第二个文本框。如果他的地址簿中有一些联系人,将显示第三个文本框。

如果有第二个或第三个文本框,用户将键入一些文本,并根据结果显示自动完成框。

每个文本框旁边都有一个名为Add的按钮,单击该按钮时我希望将文本框的值添加到客户端的列表框中。

当用户提交表单时,我想从列表框中检索所有值(这是以字符串形式的电子邮件地址列表)。

我做了什么

这是我迄今为止所做的。

public class CreateAppointmentSelectPersons
{

    [DataType(DataType.EmailAddress, ErrorMessageResourceType = typeof (Resource), ErrorMessageResourceName = "CreateAppointment_Email_Invalid_Email_Address")]
    [EmailAddress]
    [Display(ResourceType = typeof(Resource), Name = "RegisterViewModel_EmailId_Email_Id")]
    public string Email { get; set; }

    public Boolean IsSuperOfficeConnected { get; set; }

    [Display(ResourceType = typeof (Resource), Name = "CreateAppointmentSelectPersons_SelectedSuperOfficeEmail_SuperOffice_Contact")]
    public string SelectedSuperOfficeEmail { get; set; }



    public Boolean IsInternalAddressBookEmpty { get; set; }
    [Display(ResourceType = typeof(Resource), Name = "CreateAppointmentSelectPersons_InternalAddressBookPersons_AddressBook_Contact")]
    public string SelectedAddressBookPerson { get; set; }


    [Display(ResourceType = typeof (Resource), Name = "CreateAppointmentSelectPersons_AttendeesListBox_Invited_Persons")]
    [Required]
    public List<string> AttendeesListBox { get;set; }
}

并在视图方面

@using System.Web.Mvc.Html
@model DatePicker.Models.ViewModels.Appointment.CreateAppointmentSelectPersons
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
    <link href="~/Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet"/>
}

<h2>Create</h2>
@using(Html.BeginForm("Create","Appointment", new { @class = "form-horizontal", role = "form" }))
{
     @Html.AntiForgeryToken()
    <hr />
    @Html.ValidationSummary()
    <div class="form-group">

        @Html.LabelFor(m => m.Email, new { @class = "col-md-8 control-label" })
        <div class="col-md-8">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) <input type='button' id="btnEmail" class="btn-default form-inline" value="Add>>" />
        </div>

        @if (Model.IsSuperOfficeConnected)
        {
        @Html.LabelFor(m=>m.SelectedSuperOfficeEmail, new {@class="col-md-8 control-label"})
        <div class="col-md-8">

            @Html.TextBoxFor(m=>m.SelectedSuperOfficeEmail,new{@class="form-control",PlaceHolder="Search in SuperOffice..."}) <input type='button' id="btnSuperOffice" class="btn-default" value="Add>>">
        </div>

        }
        @if (Model.IsInternalAddressBookEmpty)
        {
        @Html.LabelFor(m => m.SelectedAddressBookPerson, new { @class = "col-md-8 control-label" })
        <div class="col-md-8">
            @Html.TextBoxFor(m=>m.SelectedAddressBookPerson,new{@class="form-control",PlaceHolder="Search in AddressBook..."}) <input type='button' id ="btnAddressBook" class="btn-default" value="Add>>">
        </div>
        }
        @Html.ListBoxFor(m => m.AttendeesListBox, new SelectList(Model.AttendeesListBox), new { style = "width:100%;" })
    </div>
}

@section Scripts{
    @Scripts.Render("~/Scripts/jquery-ui-1.10.4.min.js")

    <script type="text/javascript">
        $(function() {
            $("#SelectedSuperOfficeEmail").
                autocomplete({
                    source: '/Appointment/SuperOfficePerson',
                    minLength: 1,  
                    });   
        });
        $(function() {
            $("#SelectedAddressBookPerson").autocomplete({
                source: '/Appointment/AddressBookPerson',
                minLength: 1,
            });
        });
        $(function() {
            $('#btnEmail').click(function(e) {
                var name = $('#Email').val();
                $('#AttendeesListBox').append($("<option></option>").attr("value"), name).text(name);
            });
        });
        $(function () {
            $('#btnSuperOffice').click(function (e) {
                var name = $('#SelectedSuperOfficeEmail').val();
                $('#AttendeesListBox').append($("<option></option>").attr("value"), name).text(name);
            });
        });
        $(function () {
            $('#btnEmail').click(function (e) {
                var name = $('#SelectedAddressBookPerson').val();
                $('#AttendeesListBox').append($("<option></option>").attr("value"), name).text(name);
            });
        });
    </script>
}

控制器

    public JsonResult SuperOfficePerson(string term)
    {
        var persons = _connectionRepository.FindPersonsFromSuperOffice(term);
        return Json(persons.Select(p => new { label = p.FirstName + " " + p.LastName, value = p.Email}), JsonRequestBehavior.AllowGet);

    }

    public JsonResult AddressBookPerson(string term)
    {
        var userName = User.Identity.Name;
        var addressBookId = _addressBookReposiory.GetAddressBookId(userName);
        var persons = _addressBookReposiory.SearchAddressBookPersons(term, addressBookId);
        return Json(persons.Select(p => new {label = p.FirstName + " " + p.LastName, value = p.Email}), JsonRequestBehavior.AllowGet);
    }

问题

现在唯一可行的是自动完成功能 并且附加到列表框的东西不起作用。任何人都可以复习并提出建议吗?

在broswer中呈现Html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create - My ASP.NET Application</title>
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/docs.css" rel="stylesheet"/>
<link href="/Content/pygments-manni.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.7.1.js"></script>


</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" role="banner">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/">Date Picker</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="/">Home</a></li>
                    <li><a href="/Home/About">About</a></li>
                    <li><a href="/Home/Contact">Contact</a></li>
                </ul>
                <form action="/Account/LogOff" class="navbar-right" id="logoutForm" method="post"><input name="__RequestVerificationToken" type="hidden" value="9tISS1WGgT7A_GcKUS_Bezvd0y7y2K3Y6tzCcqAfTq6SwnYtmQpTxOMTP59u1ojfg5d9ReUBShCXO1caH8h16QsremZxV7qyDEvW7EjRKb3K2sHxBn0gS7dKEupjCS4rA6SbQat6xJYVde69lBQf3A2" />    <ul class="nav navbar-nav navbar-right">
        <li>
            <a href="/Account/Manage" title="Manage">Hello testaccount!</a>
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
</form>

            </div>
        </div>
    </div>

        <div class="row">
            <div class="col-md-3">
                <div class="bs-sidebar hidden-print affix" role="complementary">
                    <ul class="nav bs-sidenav">                       
                        <li class="active">
                            <a href="/AddressBook">Address Book</a>
                            <ul class="nav">                              
                                <li>
                                    <a href="/AddressBook/AddPerson">Add Contact</a>
                                </li>                               
                            </ul>
                        </li>
                        <li>
                            <a href="/Appointment/Create">Appointment</a>                           
                        </li>
                        <li>
                            <a href="/Connection">SuperOffice</a>                       
                        </li>
                    </ul>
                </div>
            </div>
        </div>      
    <div class="container body-content">

    <link href="/Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet"/>


<h2>Create</h2>
<form action="/Appointment/Create?class=form-horizontal&amp;role=form" method="post"><input name="__RequestVerificationToken" type="hidden" value="eEHQKR1V0OPt21j2EV_SeQVM7yhr7sWgHTEaXGpyroBDoJGSwc-rNm_V75iOTVNns5u5EFjXd__UhwcgnANfXWhF8Tc3n-1UgkdEiYCHYBWtSsXkNItP98neZzgKTz9KwBBdOBvws6I_1eRGvSObTw2" />    <hr />
<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li style="display:none"></li>
</ul></div>    <div class="form-group">

        <label class="col-md-8 control-label" for="Email">Email Id</label>
        <div class="col-md-8">
            <input class="form-control" data-val="true" data-val-email="The Email Id field is not a valid e-mail address." id="Email" name="Email" type="text" value="" /> <input type='button' id="btnEmail" class="btn-default form-inline" value="Add>>" />
        </div>

<label class="col-md-8 control-label" for="SelectedSuperOfficeEmail">SuperOffice Contact</label>        <div class="col-md-8">

            <input PlaceHolder="Search in SuperOffice..." class="form-control" id="SelectedSuperOfficeEmail" name="SelectedSuperOfficeEmail" type="text" value="" /> <input type='button' id="btnSuperOffice" class="btn-default" value="Add>>">
        </div>
        <label class="col-md-8 control-label" for="SelectedAddressBookPerson">AddressBook Contact</label>        <div class="col-md-8">
            <input PlaceHolder="Search in AddressBook..." class="form-control" id="SelectedAddressBookPerson" name="SelectedAddressBookPerson" type="text" value="" /> <input type='button' id ="btnAddressBook" class="btn-default" value="Add>>">
        </div>
        <select data-val="true" data-val-required="The Invited Persons field is required." id="AttendeesListBox" multiple="multiple" name="AttendeesListBox" style="width:100%;"></select>
    </div>
</form>

        <hr />
        <footer>
            <p>&copy; 2014 - InfoBridge</p>
        </footer>
    </div>

    <script src="/Scripts/jquery-2.1.0.js"></script>

    <script src="/Scripts/bootstrap.js"></script>


    <script src="/Scripts/jquery-ui-1.10.4.min.js"></script>


    <script type="text/javascript">
        $(function() {
            $("#SelectedSuperOfficeEmail").
                autocomplete({
                    source: '/Appointment/SuperOfficePerson',
                    minLength: 1,  
                    });   
        });
        $(function() {
            $("#SelectedAddressBookPerson").autocomplete({
                source: '/Appointment/AddressBookPerson',
                minLength: 1,
            });
        });
        $(function() {
            $('#btnEmail').click(function(e) {
                var name = $('#Email').val();
                $('#AttendeesListBox').append($("<option></option>").attr("value"), name).text(name);
            });
        });
        $(function () {
            $('#btnSuperOffice').click(function (e) {
                var name = $('#SelectedSuperOfficeEmail').val();
                $('#AttendeesListBox').append($("<option></option>").attr("value"), name).text(name);
            });
        });
        $(function () {
            $('#btnEmail').click(function (e) {
                var name = $('#SelectedAddressBookPerson').val();
                $('#AttendeesListBox').append($("<option></option>").attr("value"), name).text(name);
            });
        });
    </script>


<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
    {"appName":"Chrome","requestId":"9bcec3a2cd574a0ea593cf0c8113f386"}
</script>
<script type="text/javascript" src="http://localhost:4557/068bc91c7f3d4135af92f62145f0c9e6/browserLink" async="async"></script>
<!-- End Browser Link -->

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我的jquery代码错了,

  $(function() {
                $('#btnEmail').click(function(e) {
                    var name = $('#Email').val();
                    $('#AttendeesListBox').append($('<option value="'+ name +'">'+name+'</option>'));
                });

            });

            $('#btnSuperOffice').click(function (e) {
                var name = $('#SelectedSuperOfficeEmail').val();
                $('#AttendeesListBox').append($('<option value="'+name+'">'+name+'</option>'));
            });

           $('#btnEmail').click(function (e) {
                var name = $('#SelectedAddressBookPerson').val();
                $('#AttendeesListBox').append($('<option value="'+name+'">'+name+'</option>'));
            });
        });

这有效