繁体   English   中英

将行添加到ASP.NET MVC表时更新连接的数据库表

[英]Update Connected Database Table as Rows are Added to an ASP.NET MVC Table

以下代码构成了我当前正在使用的ASP.NET MVC应用程序的一部分。 索引创建了一个表,用户可以通过将标签,服务器和频率的值输入到弹出模式(通过单击“添加”按钮激活,模式HTML代码未显示)来添加行。 该表的初始值当前是通过从链接的SQL数据库表(通过使用实体框架创建)进行迁移而生成的。

我正在尝试修改此代码,以便“添加”按钮添加的任何行都将自动添加到链接的数据库表中(最好使用实体框架)。 任何帮助,将不胜感激。

调节器

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";

                }

尽管您应该为您的项目提供一个具有独立业务和数据访问层的分层体系结构 ,并且控制器应仅是传入请求的网关https://docs.microsoft.com/zh-cn/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
                }
            });
                }

您需要向控制器添加某种类型的Add方法,并用POST属性装饰。 在您的模式中,需要有一个指向控制器的add方法url的表单。 该表格应包含所有表属性的输入字段。 然后,应通过“提交”按钮将该表单发布到控制器上的add方法。 add方法需要采用提交表单的属性,创建一个新对象,然后将新对象插入数据库中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM