如何获取多个输入值并保存到Db? 这是我的输入生成器:
<div class="form-group input-group">
<input type="text" class="form-control">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-add">
+
</button>
</span>
</div>
和Jquery代码:
<script>
(function ($) {
$(function () {
var addFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $formGroupClone = $formGroup.clone();
$(this)
.toggleClass('btn-default btn-add btn-danger btn-remove')
.html('–');
$formGroupClone.find('input').val('');
$formGroupClone.insertAfter($formGroup);
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') <= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', true);
}
};
var removeFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') >= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', false);
}
$formGroup.remove();
};
var countFormGroup = function ($form) {
return $form.find('.form-group').length;
};
$(document).on('click', '.btn-add', addFormGroup);
$(document).on('click', '.btn-remove', removeFormGroup);
});
})(jQuery);
</script>
该代码通过按+按钮生成多个输入文本。
问题: 如何获取所有输入值? 在剃须刀页面和输入模型类中?
如果这只是一个输入,我可以做到。但是由javascript生成的多个输入让我厌倦了!
答案 0 :(得分:0)
问题:如何获取所有输入值?在剃须刀页面和输入模型类中?
由于您使用$formGroup.clone()
,因此可以简单地在所有输入上应用相同的name
属性,并将其另存为PageModel中的List<string>
。例如:
1.page.cshtml
@model TestInputModel
<form method="post">
<div class="form-group input-group">
<input type="text" class="form-control" name="MyAllInputs">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-add">
+
</button>
</span>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
@section Scripts{
<script>...</script>
}
2.PageModel
public class TestInputModel : PageModel
{
//using your db context by DI
private readonly MyApplicationDbContext _context;
public TestInputModel(MyApplicationDbContext context)
{
_context = context;
}
//bind your all inputs' values
[BindProperty]
public List<string> MyAllInputs{ get; set; }
public void OnGet()
{
}
public void OnPost()
{
//logic to save you input values to dbcontext
var data = MyAllInputs;
//...
}
}