简体   繁体   English

在 ASP.NET MVC 中动态添加文本框

[英]Add textboxes dynamically in ASP.NET MVC

I work on an ASP.NET MVC project that I need some help with.我在一个 ASP.NET MVC 项目上工作,我需要一些帮助。 I need to be able to create x number of textboxes when the user click "add textbox".当用户单击“添加文本框”时,我需要能够创建 x 个文本框。 When the user enter the page a viewmodel is loaded.当用户进入页面时,会加载一个视图模型。 This viewmodel need to handle the x number of textboxes that the user create when he is on the page so that when the page is posted these textboxes are part of the model.这个视图模型需要处理用户在页面上创建的 x 个文本框,以便在页面发布时这些文本框成为模型的一部分。 The model should look something like this..该模型应该看起来像这样..

public class PlanViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public List<EventViewModel> EventList { get; set; } // this should be the list of textboxes that the user "create" by clicking add new
}

public class EventViewModel
{
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public string Description { get; set; }
}

I'm kinda lost on how to do this so any help is appreciated.我有点迷失在如何做到这一点,所以任何帮助表示赞赏。

UPDATE更新

I've added this javascript that add textboxes client side..我添加了这个添加文本框客户端的javascript..

<script type="text/javascript">
function GetDynamicTextBox(value) {
    return('<input type="text" name="events[0].Key" value="box1" /><input type="text" name="events[0].Value.StartDate" value="box2"/><button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>');
}
function AddTextBox() {
    var div = document.createElement('DIV');
    div.innerHTML = GetDynamicTextBox("");
    document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(div) {
    document.getElementById("divcontent").removeChild(div.parentNode);
}
</script>

            <div id="divcontent" class="form-group">
            <button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
        </div>

I think I only need to add unique id's for the textboxes like this...我想我只需要为这样的文本框添加唯一的 id ......

events[0].Key
events[1].Key
events[2].Key

and so on..等等..

But I don't know how.但我不知道怎么做。 Anyone knows?有谁知道?

You can add a list of String, like this您可以像这样添加字符串列表

public String[] MyTextFields

and then create HTML using Javascript, like this:然后使用 Javascript 创建 HTML,如下所示:

<input name="myTextFields[0]"></input>

<input name="myTextFields[1]"></input>

In Razor view:在剃刀视图中:

@for (var i = 0; i < Model.EventList.Count; i++)
{
    @Html.EditorFor(x => Model.EventList[i].Name)
}

To set the name attribute of all edited elements in javascript, this is to be called on page load, and any time the collection changes (item is added or removed):要在 javascript 中设置所有已编辑元素的 name 属性,这将在页面加载时调用,并且在集合更改(添加或删除项目)时调用:

var children = document.getElementById("myDIV").children; // TODO: here supposing children are the input elements, may be different on your page (they may be nested in a different way)
for (i = 0; i < children.length; i++)
{
    var el = children[i];
    el.name = 'EventList[' + i + '].Name'; // TODO: look into source code of the generated page for the actual format of existing elements and then modify the mask accordingly
    el.id = 'EventList[' + i + '].Name';
}

If it is ok to have JS dependency than I suggest to use light Knockout library.如果可以依赖 JS,我建议使用轻量级 Knockout 库。 It will help you to create/edit/delete your inputs.它将帮助您创建/编辑/删除您的输入。 Check example in JS fiddle .检查 JS fiddle 中的示例

Use HTML to adjust your view.使用 HTML 调整您的视图。 Tag data-bind lets you to bind to data and events标签数据绑定让你绑定到数据和事件

<button data-bind="click: addInput">Add</button>
<div data-bind="foreach: inputs">
  <input data-bind="value: text"/><br />
</div>
<button data-bind="click: proceed">Proceed</button>
<!-- Use Knockout JS library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>

Then small JS script which handles adding new input and processing data on click.然后是处理点击添加新输入和处理数据的小型 JS 脚本。

function InputData(text) {
  let self = this;
  self.text = text;
}
function InputViewModel() {
  let self = this;
  // Your array of HTML inputs
  self.inputs = ko.observableArray([new InputData("Default value")]);
  self.output = ko.observable();
  self.addInput = function() {
    // Dynamically adds new input on user click button "Add"
    self.inputs.push(new InputData(""));
  };
  self.proceed = function() {
    // Process all input with their values
    for (var i = 0; i < self.inputs().length; i++) {
        console.log(self.inputs()[i].text);
    }

  }
}
// Bind our JS to HTML view
ko.applyBindings(new InputViewModel());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM