【问题标题】:Add items in listbox in view when button is clicked单击按钮时在视图中添加列表框中的项目
【发布时间】:2014-01-31 21:00:06
【问题描述】:

我有这个模型

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

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

我应该怎么做才能使我的视图正常工作,以便在单击按钮时将值添加到列表框中,并且在提交时我只获得列表框的值

【问题讨论】:

  • 公共列表框参加者列表框 { 获取;设置;什么是 ListBox 类型?
  • 第一次听说,ListBox 用作类型。你确定 ListBox 类是这样使用的吗? Lambda 表达式是一个类型错误。
  • 我不知道,这就是我提到Also, i'm new to listbox in view. 的原因。我以前从未使用过它,我猜这就是它的工作原理。

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


【解决方案1】:

解决方案来了 -

让你的模型成为 -

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

让你的控制器动作成为 -

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

索引控制器只是简单地创建项目列表并将其发送到索引视图。索引视图将是 -

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

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

当您在 ListBox 中选择项目并单击 Submit 按钮时,表单将与选定的值一起提交给 Listbox Controller 的 Submit Action。

更新

根据问题更新,为了将所有 ListBox 项发送到服务器,我们使用 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" />
}

在控制器中 -

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

        return null;
    }

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

【讨论】:

  • 实际上,我希望提交列表框中的所有值。
  • 你不会在 ListBox 中获得项目的原因是 FORM Post 只会提交输入的值。如果不提交下拉列表或列表框的选项。如果您需要所有选项,则需要将它们作为隐藏字段添加到表单中并取回。
  • 如何在隐藏域中添加?
  • 你只想要用户在客户端添加的项目吗?
  • 是的。最初列表框需要为空,然后用户在列表框中添加项目,然后应该提交列表框中的所有值让我们说一个按钮点击(假设提交)你可以来聊天室吗?这样我就可以正确地解释事情了。或许你可以提供更好的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 2020-07-26
相关资源
最近更新 更多