MVC Core使用ajax发布数据并刷新页面上的部分 [英] MVC Core use ajax to post data and refresh a section on the page

查看:435
本文介绍了MVC Core使用ajax发布数据并刷新页面上的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在AspNet Core 2.0 MVC网站上工作. 问题是: 我在一个页面中有2个表单,第一个表单用于提交模型,这是通过以下操作完成的:

I'm working on AspNet Core 2.0 MVC site. The problem is: I have 2 forms in one page, the first form is for submitting a Model, this is done via this action:

    [HttpPost]
    public IActionResult AddProductToSale([FromForm]ProductViewModel product)
    {
        ProductViewModel p = new ProductViewModel()
        {
            Id = 1,
            Gender = GenderType.Ambos,
            AvailableStock = 5,
            Name = "Zapatillas Nike",
            Size = "42",
            Type = ProductType.Zapatillas,
            UnitPrice = 1500
        };

        SaleViewModel.Products.Add(p);

        return Json(p);
    }

.js脚本是:

function addProductToSale() {
    $.ajax({
        url: '/Home/AddProductToSale',
        type: "POST",
        dataType: "html",
        data: $("#frmAddProduct").serialize(),
        success: function (data) {
            console.log(data);
        },
        error: function () { alert('error'); }
    });
}

数据可以通过javascript正常运行.但是我还有另一种形式可以保存以前添加的所有产品.这是我不知道如何实现的. 有人可以为我提供有关如何刷新页面第二部分的线索吗?

The data is travelling fine through the javascript to the action. But I have another form to hold all the Products added previously. This is what I don't know how to implement. Can someone give me a clue on how to refresh the second section of the page?

预先感谢

推荐答案

如果要使用新添加的产品更新页面的一部分,则可以采用多种方式

If you want to update a section of the page with the newly added product, you can do it in multiple ways

1.用一个新的ajax调用重新加载整个列表

成功保存新产品的ajax调用后,可以再次调用ajax以再次加载整个列表.您将在第一个ajax调用的done事件中进行此调用.

When your ajax call to save new product is successful, you can make another ajax call to load the entire list again. You will make this call in the done event of the first ajax call.

例如,假设您以表格数据形式呈现页面中的产品列表.

For example, let's say, you are rendering the list of products in the page in tabular data form

<div id="product-list" data-url="@Url.Action("ProductList")">
  <!-- Your code to render the table which displays the list of products -->
</div>

在脚本中

function addProductToSale() {
    $.ajax({
        url: '@Url.Action("AddProductToSale")',
        type: "POST",
        data: $("#frmAddProduct").serialize()
    }).done(function(res) {
            var $productList= $("#product-list");
            var url=$productList.data("url");
            $productList.load(url);
        }
    }).fail(function(a, b, c) {
        console.log(c);
    });
}

假设您有一个action方法,该方法返回呈现产品列表所需的标记

Assuming you have an action method which return the markup needed to render the list of products

public IActionResult ProductList()
{
  var list = new List<ProductViewModel>();
  // to do :Load this list from the database
  return PartialView(list);
}

然后在部分视图(强类型为ProductViewModel)中,您将渲染表格

And in the partial view, which is strongly typed to ProductViewModel you will render the table

@model List<ProductViewModel>
<table class="table">
  @foreach(var item in Model)
  {
     <tr>
         <td>@item.Name</td>
     </tr>
  }
</table>

2.让AddProductToSale返回新产品的JSON响应

通过这种方法,您的AddProductToSale将返回新视图模型对象的JSON表示,并且在done事件中,您可以为新表行构建标记并将其追加到现有表中.

In this approach, your AddProductToSale will return a JSON representation of the new view model object and in the done event, you can build the markup for the new table row and append it to the existing table.

在这种情况下,我们假设您已经有一个表

In this case, let's assume you already have a table

<div id="product-list">
    <table class="table" id="tbl-list">
        <tr><td>Product 1</td></tr>
        <tr><td>Product 2</td></tr>
    </table>
</div>

done事件中

 done(function(product) {
    var $tbl= $("#tbl-list");
    var r='<tr><td>'+product.name+'</td></tr>';
    $tbl.prepend(r);
 }

在这里,我们正在为javascript中的行手动创建标记,并使用jQuery prepend方法将其添加到表格顶部.

Here we are manually creating the markup for the row in javascript and use jQuery prepend method to add it to the top of the table.

另一个选择是进行ajax调用,以从服务器获取新表行的标记,您将传递新创建的ID(您的Add方法应返回该ID),并将其传递给将读取的方法使用id记录,并返回单行的标记,然后将其添加到表中.

Another option is to make an ajax call to Get the markup for the new table row from server, you will pass the newly created Id (which your Add method should return) and you will pass that to a method where it will read the record using id and return the markup for the single row and prepend it to the table.

[HttpPost]
public IActionResult AddProductToSale([FromForm]ProductViewModel product)
{
    // to do : Save 
    return Json(new { status="success", id= 101 }); // to do : Get the real id
}

在ajax调用中,

.done(function(res) {
            if (res.status === 'success') {
                var $tbl = $("#tbl-list");
                $.get('/Product/GetProductRow?id='+res.id,function(r) {
                   $tbl.prepend(r);
                });
            }
        })

假设您有一个GetProductRow方法,该方法返回新行的标记

Assuming you have a GetProductRow method which returns the markup for the new row

public IActionResult GetProductRow(int id)
{
    var t = _context.Products.FirstOrDefault(a => a.Id == id);
    return Content("<tr><td>" + t.Name + "</td></tr>");
}

我只是在此处对标记进行了硬编码并以字符串形式返回,但是您可以返回返回标记的局部视图

I just hard coded the markup here and returning as a string, but you can return a partial view which returns the markup

这篇关于MVC Core使用ajax发布数据并刷新页面上的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆