Я хотел бы вставить несколько записей в мою таблицу под названием «sibling», используя свой метод Create (который я создал автоматически с помощью методов Scaffolding). Я добавил динамическую форму добавления полей. Однако, когда я нажимаю кнопку «Отправить», она получает только первую запись.Как вставить несколько строк в одну таблицу? (MVC 5 ASP.NET)
У меня есть идея, реализуя «foreach» в указанном методе, но я не могу найти ответ, который находится на месте. Специально для моего случая я просто хочу изменить метод Create для «sibling», который был сгенерирован автоматически (если такой способ не требуется, чтобы создать новый метод, но если нет, то я тоже хорошо разбираюсь в другом подходе).
Это мой SiblingController:
public ActionResult Create(int id)
{
var sib = new sibling();
sib.child_id = id;
return View(sib);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "sibling_id,child_id,age,gender")] sibling sibling)
{
if (ModelState.IsValid)
{
db.siblings.Add(sibling);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.child_id = new SelectList(db.children, "child_id", "last_name", sibling.child_id);
return View(sibling);
}
Это мой Create.cshtml для Sibling:
@model dummyApp.Schema.TestModels.sibling
@{
ViewBag.Title = "Create";
}
@section Scripts{
<script type="text/javascript">
//Coding
$("#numBox").change(function() {
var htmlString = "";
var len = $(this).val();
for (var i = 0; i < len; i++) {
htmlString += ' <div class="form-group">\
@Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { @class = "control-label col-md-2" })\
<div class="col-md-10">\
@Html.EditorFor(model => model.child_id, new { htmlAttributes = new { @class = "form-control" }})\
@Html.ValidationMessageFor(model => model.child_id, "", new { @class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
@Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })\
<div class="col-md-10">\
@Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })\
@Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
@Html.LabelFor(model => model.gender, htmlAttributes: new { @class = "control-label col-md-2" })\
<div class="col-md-10">\
@Html.EditorFor(model => model.gender, new { htmlAttributes = new { @class = "form-control" } })\
@Html.ValidationMessageFor(model => model.gender, "", new { @class = "text-danger" })\
</div>\
</div>\
';
}
$("#adtnl_fields").html(htmlString);
})
</script>
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>sibling</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<!--
<div class="form-group">
@Html.LabelFor(model => model.sibling_id, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.sibling_id, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.sibling_id, "", new { @class = "text-danger" })
</div>
</div>
-->
<div class="form-group">
@Html.Label("Number of Siblings:", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="number" id="numBox" class="form-control"/>
</div>
</div>
<!--
<div class="form-group">
@Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*Html.DropDownList("child_id", null, htmlAttributes: new { @class = "form-control" })*@
@Html.EditorFor(model => model.child_id, new { htmlAttributes = new { @class = "form-control" }})
@Html.ValidationMessageFor(model => model.child_id, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.gender, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.gender, "", new { @class = "text-danger" })
</div>
</div>
-->
<!-- Div for additional fields -->
<div id="adtnl_fields">
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Это мой 'sibling.cs':
public partial class sibling
{
public int sibling_id { get; set; }
public int child_id { get; set; }
public Nullable<int> age { get; set; }
public string gender { get; set; }
public virtual child child { get; set; }
}
Пожалуйста, помогите , Спасибо!
Вы должны опубликовать список братьев и сестер вашего метода действия и ваш метод действия должны также принять коллекцию объекта братьев и сестер. Также вы не можете использовать вызов метода HtmlHelper (который является методом сервера) внутри вашего javascript-метода, который выполняется на стороне клиента. – Shyju