简体   繁体   English

使用jquery ajax发布和获取数据,仅在mvc中更新html表行

[英]post and get data using jquery ajax and update html table row only in mvc

I have a HTML table and I want that when the user clicks on the Count cell, the data for that row is updated in the database and the result is also updated in that row. 我有一个HTML表,我希望当用户单击“计数”单元格时,该行的数据在数据库中更新,并且结果也在该行中更新。 I only want to update that row and not the whole page. 我只想更新该行而不是整个页面。 This is what I have so far: 这是我到目前为止的内容:

View (the view contains a partial view that represents a row: 视图(该视图包含表示一行的局部视图:

<table class="table table-striped table-bordered table-condensed table-hover">
    <tbody>
        @foreach (var item in Model)
        {
            <div class="@item.ProductID">
                @Html.Partial("TableTransactionsTableRow", item)
            </div>
        }

        @if (!string.IsNullOrEmpty(log.Opmerking))
        {
            <tr>
                <td></td>
                <td>@log.Opmerking</td>
                <td></td>
            </tr>
        }
    </tbody>
</table>

Model: 模型:

public class Transaction
{
    private int ProductID { get; set; }
    private int Count { get; set; }
    private string Description { get; set; }
    private decimal Total { get; set; }
}

Partial view (TableTransactionRow): 局部视图(TableTransactionRow):

@model Transaction

<tr>
    <td class="text-right" style="width: 20%;">
        <a class="CountClick" href="@Url.Action("UpdateProductCount", "Tables", new { productID = Model.ProductID, count = -1 })">
            <div>
                @Model.Count
            </div>
        </a>
    </td>
    <td>
        <a href="@Url.Action("UpdateProductCount", "Tables", new { productID = Model.ProductID, count = 1 })">
            <div>
                @Model.Description
            </div>
        </a>
    </td>
    <td class="text-right" style="width: 20%;">@Model.Total</td>
</tr>

Ajax script: Ajax脚本:

$(document).ready(function () {
    $('.CountClick').click(function () {
        var productID = getParameterByName('productID', $(this).attr("href"));        
        var id = "#" + productID;

        $.ajax({
            cache: false,
            url: $(this).attr("href"), // used data from url
            datatype: "text",
            type: "POST",
            success: function (data) {
                $(id).html(data);
            },
            error: function () {
                $(id).html("ERROR");
            }
        });
        return false;
    });
});

The TablesController: TablesController:

public ActionResult UpdateProductCount(int? productID, int? count)
{
    if (productID.HasValue)
    {
        Transaction t = new Transaction();
        t.Count += count.Value;
        t.Total= t.Count * t.Price;
        //save the transaction to the database and return it to the partial view
        return PartialView("TableTransactionsTableRow", t);
    }
    return RedirectToAction(MVCItems.TableTransactions);
}

How can I update the values in the cells without refreshing the whole table? 如何在不刷新整个表的情况下更新单元格中的值? Any help is appreciated. 任何帮助表示赞赏。

After thinking for a while I have solved the problem. 经过一段时间的思考,我已经解决了问题。 I used this answer as base of my solution. 我以这个答案为基础。 So I return a json object of the Transaction from the controller to ajax jQuery. 所以我将事务的json对象从控制器返回给ajax jQuery。 I have removed the partialview and used the html as a row within the main view. 我已经删除了partialview,并将html用作主视图中的一行。 I have set id's for div of the count and total div element. 我已经为计数和总div元素的div设置了id。 When I return the json object to the view I update the values by using element.innerText . 当我将json对象返回到视图时,我使用element.innerText更新了值。

Controller: 控制器:

public ActionResult UpdateProductCount(int? productID, int? count)
    {
        if (productID.HasValue)
        {

Transaction t = new Transaction();
    t.Count += count.Value;
    t.Total= t.Count * t.Price;

            if (transaction == null)
                return Json(t, JsonRequestBehavior.AllowGet);           

    }

jQuery: jQuery的:

$(document).ready(function () {
$('.CountClick').click(function () {

    var productID = getParameterByName('productID', $(this).attr("href"));        
    var countID = "Count" + productID;
    var totalID = "Total" + productID;

    var countElement = document.getElementById(countID);
    var totalElement = document.getElementById(totalID);
    var rowElement = document.getElementById(productID);

    $.ajax({
        cache: false,
        url: $(this).attr("href"), // used data from url
        datatype: "text",
        type: "POST",
        success: function (response) {

            var count = parseInt(response.Count);

            if (count > 0)
            {
                countElement.innerText = response.Count;
                totalElement.innerText = response.Total;
            }
            else
            {
                rowElement.innerHTML = "";
            }
        },
        error: function () {
            $("#divResult").html("ERROR");
        }
    });

    return false;
});
});

Hope this helps someone else in the future. 希望这对以后的人有所帮助。

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

相关问题 POST方法发送RAW TEXT数据并使用Jquery AJAX Web方法获取HTML响应并使用POSTMAN进行检查 - POST method to send RAW TEXT data and get HTML Response using Jquery AJAX Web Method and check with POSTMAN MVC更新表数据的各个行POST - MVC Updating individual row of table data POST How to insert HTML table data into SQL Server in a single batch by using jquery ajax and structured parameter with ASP.NET MVC controller - How to insert HTML table data into SQL Server in a single batch by using jquery ajax and structured parameter with ASP.NET MVC controller 使用Ajax / MVC在表格行中显示图像 - Display an image in a table row using Ajax/MVC C#MVC4 Jquery Ajax发布部分视图更新 - C# MVC4 Jquery Ajax Post Partial View Update 如何使用 AJAX 发布数据以更新我的 MVC 视图 - How can I post data using AJAX to update my MVC View 使用jquery的每种方法并从表MVC模型中获取数据 - using jquery each method and get data from table MVC Model 如何使用(Jquery)或(Jquery和Ajax)在MVC Core中将数据插入到明细表中 - How to insert data to details Table in mvc core using (Jquery) or (Jquery and Ajax) Jquery/Ajax 更新表[ASP.NET Core MVC] - Jquery/Ajax to update a TABLE[ASP.NET Core MVC] MVC 4-jQuery Ajax将完整格式的数据发布到特定方法 - MVC 4 - jQuery Ajax Post Full Form Data to Specific Method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM