我正在嘗試創建一個頁面,您可以在其中按下按鈕“添加選項”,并<input asp-for>在運行時將另一個添加到表單中,然后將新添加<input asp-for>的 ' 值附加到模型的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; }
任何幫助表示贊賞。
uj5u.com熱心網友回復:
添加一個帶有類名的 div option-container。
<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 默認包含在 .net mvc 中),這將為您的按鈕添加一個單擊事件,該事件將添加輸入欄位。
@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>
}
在您的表單中點擊提交,在您的代碼上添加一個斷點并檢查新的輪詢選項是否系結到模型。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429382.html
標籤:javascript jQuery asp.net-mvc asp.net-core-mvc
