c# - 单击按钮时在 View 中的列表框中添加项目

标签 c# jquery asp.net-mvc listbox

我有这个型号

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; }
}

另外,我对 View 中的列表框很陌生。 这个想法是用户最多有三个框,当他们输入电子邮件地址并单击旁边的按钮时,我想将其添加到 View 中的列表框中,我想仅在发布表单时从列表框中检索值.

这就是我目前所看到的,

@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>
}

现在我收到一条提示“无法解析 ListBoxFor(lambda 表达式)”。

我应该做什么,让我的 View 工作,以便在单击按钮时将值添加到列表框中,并且在提交时我只获得列表框的值

最佳答案

这是解决方案 -

让你的模型是 -

public class ListBoxModel
{
    public List<string> Names { get; set; }
    public List<string> SelectedNames { get; set; }
}

让你的 Controller Action -

public class ListBoxController : Controller
{
    public ActionResult Index()
    {
        ListBoxModel model = new ListBoxModel();
        model.Names = new List<string>();
        model.Names.Add("Rami");
        return View(model);
    }

    public ActionResult Submit(ListBoxModel model)
    {
        return null;
    }
}

索引 Controller 只是创建项目列表并将其发送到索引 View 。索引 View 将是 -

@model MVC.Controllers.ListBoxModel

@{
    ViewBag.Title = "Index";
}

<h2>View1</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $('#click1').click(function (e) {

            var name = $("#txt1").val();

            $('#SelectedNames').
                append($("<option></option>").
                attr("value", name).
                text(name));
        });
    });
</script>

@using (Html.BeginForm("Submit", "ListBox", FormMethod.Post))
{
    @Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.Names))

    <input type="text" id="txt1" />
    <input type="button" value="Click" id="click1" />

    <input type="submit" value="submit"/>
}

在索引 View 中,当您在文本框中输入名称并单击“单击”按钮时,它将被添加到客户端的列表框中 -

enter image description here

当您在列表框中选择项目并单击“提交”按钮时,表单将连同所选值一起提交到列表框 Controller 的“提交操作”。

enter image description here

更新

根据问题更新,为了将所有列表框项发送到服务器,我们使用 JQuery 在表单中动态添加隐藏字段。

查看 -

@model MVC.Controllers.ListBoxModel

@{
    ViewBag.Title = "Index";
}

<h2>View1</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>

    $(function () {
        $('#click1').click(function (e) {

            var name = $("#txt1").val();
            $('#SelectedNames').
                append($("<option></option>").
                attr("value", name).
                text(name));

            $('#hiddensq').append("<input name='UserValues' type='hidden' value='"+ name +"'/>");
        });
    });
</script>

@using (Html.BeginForm("Submit", "ListBox", FormMethod.Post))
{
    <div id="hiddensq">
    </div>

    for (int i = 0; i < Model.Names.Count; i++)
    {
        @Html.Hidden("UserValues", Model.Names[i]);
    }

    @Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.Names))

    <input type="text" id="txt1" />
    <input type="button" value="Click" id="click1" />

    <input type="submit" value="submit" />
}

在 Controller 中 -

    public ActionResult Submit(ListBoxModel model, IEnumerable<string> UserValues)
    {
        var c = Request.Form;

        return null;
    }

输出 - 所有选定的值都将出现在 ListBoxModel 中,但所有列表框项目将出现在 UserValues 参数中。

enter image description here

关于c# - 单击按钮时在 View 中的列表框中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21476073/

相关文章:

c# - 不了解在系统架构中的何处创建 IoC 容器

c# - Sharepoint 客户端对象模型更新仅一个文件夹的属性

javascript - Sweetalert2 不返回真/假

asp.net-mvc - 我如何对这个业务逻辑进行单元测试?

asp.net-mvc - Web 部署项目中的编译错误 "Could not load type ' System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo >'"。 Asp.net mvc rc2

asp.net - 我怎样才能让asp.net mvc显示一个漂亮的500错误消息?

c# - DDD - 使用聚合的 transient 验证

javascript - JQuery 将项目添加到我的 JSON

javascript - 如何通过单击特定段落来激活事件

c# - c# 中的选项类型替代方案