问题
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);
}
the .js scripts is:
function addProductToSale() {
$.ajax({
url: '/Home/AddProductToSale',
type: "POST",
dataType: "html",
data: $("#frmAddProduct").serialize(),
success: function (data) {
console.log(data);
},
error: function () { alert('error'); }
});
}
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?
Thanks in advance
回答1:
If you want to update a section of the page with the newly added product, you can do it in multiple ways
1. Reload the entire list with a new ajax call
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>
In the script,
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);
});
}
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);
}
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. Have the AddProductToSale return JSON response for the new product
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>
And in the done
event
done(function(product) {
var $tbl= $("#tbl-list");
var r='<tr><td>'+product.name+'</td></tr>';
$tbl.prepend(r);
}
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.
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
}
And in the ajax call,
.done(function(res) {
if (res.status === 'success') {
var $tbl = $("#tbl-list");
$.get('/Product/GetProductRow?id='+res.id,function(r) {
$tbl.prepend(r);
});
}
})
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
来源:https://stackoverflow.com/questions/46996432/mvc-core-use-ajax-to-post-data-and-refresh-a-section-on-the-page