Следующий код составляет части приложения ASP.NET MVC, над которым я сейчас работаю. Индекс создает таблицу, в которой пользователь может добавлять строки, вводя значения для тега, сервера и частоты во всплывающем модальном окне (активируется нажатием кнопки «Добавить», модальный HTML-код не отображается). Начальные значения таблицы в настоящее время генерируются путем миграции из связанной таблицы базы данных SQL (созданной с помощью entity-framework).
Я пытаюсь изменить этот код, чтобы любые строки, добавленные кнопкой «Добавить», автоматически добавлялись в связанную таблицу базы данных (желательно с использованием структуры сущностей). Любая помощь будет оценена по достоинству.
Контроллер
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
ExampleDB _db = new ExampleDB();
public ActionResult Index()
{
var model = _db.TData.ToList();
return View(model);
}
protected override void Dispose(bool disposing)
{
if (_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
Классы
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
Индекс
@model IEnumerable<ExampleWebAppilcationTest.TableData>
@{
ViewBag.Title = "Home Page";
}
@{
ViewBag.Title = "Index";
}
<h2>Table Data</h2>
<table class = "table table-bordered" id = "mainTable">
<thead>
<tr>
<th></th>
<th class = "thTag" scope = "col">
@Html.DisplayNameFor(model => model.Tag)
</th>
<th class = "thServer" scope = "col">
@Html.DisplayNameFor(model => model.Server)
</th>
<th class = "thFreq" scope = "col">
@Html.DisplayNameFor(model => model.Frequency)
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan = "5">
@foreach (var item in Model)
{
<tr>
<td><input type = "checkbox"/></td>
<td>
@Html.DisplayFor(modelItem => item.Tag)
</td>
<td>
@Html.DisplayFor(modelItem => item.Server)
</td>
<td>
@Html.DisplayFor(modelItem => item.Frequency)
</td>
</tr>
</tbody>
</table>
<button type = "button" id = "addBtn" class = "btn btn-success">Add</button>
<!-- The Modals -->
<script>
var table = document.getElementById('mainTable');
// Get the modal
var addmodal = document.getElementById('addModal');
// When the user clicks the button, open the modal
btn.onclick = function () {
addmodal.style.display = "block";
}
var sbtn = document.getElementById("subBtn");
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
var objInputCheckBox = document.createElement("input");
objInputCheckBox.type = "checkbox";
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.appendChild(objInputCheckBox);
cell2.innerHTML = tag;
cell3.innerHTML = server;
cell4.innerHTML = frequency;
addmodal.style.display = "none";
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вам нужно добавить какой-то метод Add к вашему контроллеру, украшенный атрибутом POST. В вашем модальном окне должна быть форма, указывающая на URL-адрес метода добавления контроллера. Форма должна содержать поля ввода для всех свойств вашей таблицы. Затем эту форму следует отправить с помощью кнопки отправки в метод добавления на вашем контроллере. Метод добавления должен взять свойства отправленной формы, создать новый объект, а затем вставить новый объект в базу данных.
Хотя у вас должен быть Многослойная архитектура для вашего проекта с отдельными уровнями Business и DataAccess, а контроллер должен быть только шлюзом для входящих запросов https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design)
Вот что вы можете сделать с текущей настройкой:
Контроллер:
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
using (var dbContext = new ExampleDB())
{
var model = dbContext.TData.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(TableData data)
{
using (var dbContext = new ExampleDB())
{
dbContext.TData.Add(data);
dbContext.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
Доступ к данным
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public ExampleDB() : base(nameOrConnectionString: "Your Database Connection String") { }
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
Вид
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
//Here fetch all data in a class
var data = { Tag: tag, Server: server, Frequency: frequency };
//make ajax call to add data
$.ajax({
type: "POST",
url: '@Url.Action("Index", "Home")', //your action
data: data,
dataType: 'json',
success: function (result) {
//to close the popup
},
error: function (result) {
//to show error message
}
});
}
Я понял проблему. В вашем вызове ajax URL-адрес должен быть «/ Home / Index», а не «/ Index / Home». Спасибо за помощь. Если у вас будет возможность, обновите свой ответ.
Ах ... Обновил ответ с помощью @ Url.Action. Отметьте его как ответ, если он окажется полезным.
После этих изменений в таблице базы данных по-прежнему не отображаются дополнительные строки.