ASP.NET MVC/JavaScript 使用JS和链接元素将表单元素添加到模型中



我正在尝试创建一个页面,在该页面中,您可以按下"添加选项"按钮,它会在运行时向表单添加另一个<input asp-for>,然后将新添加的<input asp-for>的值附加到Model的IEnumerable<PollOption>

如果可能的话,使用JavaScript的最佳方法是什么?

这是我的:

index.cshtml

<form method="post">
<div id="optionsContainer" class="col-8 pt-4">
<div class="form-group row">
<div class="col-6 text-center text-light">
Poll Title
</div>
<div class="col-6">
<input asp-for="PollTitle" class="form-control" />
</div>
</div>
<br />
<div class="form-group row">
<button id="addNewOptionBtn" class="btn btn-primary">Add New Option</button>
<div class="col-6 text-center text-light">
Options:
</div>
</div>
</div>
<button type="submit" class="btn btn-success form-control">Create Poll</button>
</form>

PollModel

[BsonId]
public ObjectId Id { get; set; }
public int PollId { get; set; }
public string? PollTitle { get; set; }
public IEnumerable<PollOptionModel>? PollOptions { get; set; }
public DateTime? CreatedAt { get; set; }
public bool IsActive { get; set; }

PollOptionModel

[BsonId]
public ObjectId Id { get; set; }
public int OptionId { get; set; }
public string? Option { get; set; }

感谢您的帮助。

添加一个类名为option-container的div。

<form method="post">
...
<div class="form-group row">
<button id="addNewOptionBtn" class="btn btn-primary">Add New Option</button>
<div class="col-6 text-center text-light">
Options:
<div class="option-container">
</div>
</div>
</div>
...
</form>

然后添加这个脚本(jquery默认包含在.netmvc中(,这将向按钮添加一个点击事件,该事件将添加输入字段。

@section scripts {
<script>
$(document).ready(function(){
// click event
$("#addNewOptionBtn").click(function(e){
e.preventDefault();
// this will be used as the index of the Ienumerable
var count = $(".options").length;
// new input fields to be inserted
var newOption = "<input name='PollOptions["+count+"].OptionId' placeholder='Option ID' value='"+count+"' /><input name='PollOptions["+count+"].Option' placeholder='Option' /><br/><br/>";
// insert the new input fields
$(newOption).appendTo(".option-container");
})
});
</script>
}

点击表单中的submit,在代码中添加断点,然后检查新的民意调查选项是否绑定到模型。

最新更新