将数据绑定到 ListBox 并将列表发布到数据库 mvc5

Binding data to a ListBox and posting the list to database mvc5

我正在使用代码优先方法开发一个 mvc5 应用程序。在我的一个视图中,我有一个文本框、一个添加按钮、一个保存按钮、一个删除按钮和一个列表框。

当我在文本框(文本)中输入一个值并单击添加按钮时,它应该被添加到列表框中并显示文本。因此,此列表框中将有多个文本。而且我应该能够使用删除按钮删除列表框中的 record/records。

之后我想 post 将此列表发送到服务器。我想这种情况下的大部分任务都可以使用 Jquery 完成。

到目前为止我做了什么

在_AttributeCreate局部视图中

@model eKnittingData.AttributeViewModel

@using (Html.BeginForm("Save", "Attribute"))
{ 
   @Html.TextBox("abc")
   <input type="button" name="AddText" value="Add Text" id="AddText" />

    @Html.ListBoxFor(a => a.typevalue, new SelectList(Model.typevalue, "Id", "Text"))


    <input type="submit" value="Save" id="btn" class="btn btn-success" onclick="disableBtn()" />
}  

附加项目的脚本

<script>
        $('#AddText').click(function () {
            $('#typevalue').append(
                new Option($('input[name=abc]').val()));
        });  
</script>

AttributeViewModel

public class AttributeViewModel
{
    public IEnumerable<String> typevalue { get; set; }
}

但这不起作用。请指导我如何执行此操作(包括删除功能和最终 post 功能)。提前致谢!

您的代码和实现存在一些问题。 @Html.ListBoxFor(a => a.typevalue, new SelectList(Model.typevalue, "Id", "Text")) 将不起作用,因为 typevalueIEnumerable<String> 并且 string 不包含名为 IdText 的属性。虽然您可以只使用 @Html.ListBoxFor(a => a.typevalue, null) 列表框不适合您尝试做的事情。列表框(<select multiple> 元素)仅回传其选定选项的值,因此除非在提交表单时选择所有选项,否则您不会获得预期的结果。

从您想要动态添加新项目的评论中添加到 typevalue collection,并能够删除它们。您的 html 应该类似于

@using (Html.BeginForm("Save", "Attribute"))
{
  <input type="text" id="newtypevalue" />
  <input type="button" value="Add Text" id="addtypevalue" />
  <div id="typevaluelist">
    // Generate inputs for existing items and in case of returning the view
    foreach(var item in Model.typevalue)
    {
      <div class="typevalue">
        <input type="text" name="typevalue" value="@item" />
        <button type="button" class="delete">Delete</button>
      </div>
    }
  </div>
  ....
}
// Hidden template for adding new items (outside the form element)
<div id="new" style="display:none;">
  <div class="typevalue">
    <input type="text" name="typevalue" />
    <button type="button" class="delete">Delete</button>
  </div>
</div>

并添加以下用于添加和删除项目的脚本

$('#addtypevalue').click(function() {
  var clone = $('#new').clone().children('div'); // copy the template
  clone.find('input').val($('#newtypevalue').val()); // update text
  $('#typevaluelist').append(clone); // add it to the DOM
  $('#newtypevalue').val(''); // clear initial text box
});
$('#typevaluelist').on('click', '.delete', function() {
  $(this).closest('.typevalue').remove(); // remove it from the DOM
});

参考this fiddle