Reputation: 386
I can pass an object to be edited from my view to my Upsert action method , using Tag-Helpers like this ...
This is my Index.cshtml:( Take a look at Edit link bellow)
@foreach (var item in Model)
{
<tr>
<td>@item.CategoryID </td>
<td>@item.CategoryName </td>
<td>
<a asp-area="Admin" asp-controller="Category" asp-action="Upsert" asp-route-CategoryID="@item.CategoryID" asp-route-CategoryName="@item.CategoryName">Edit</a>
</td>
</tr>
}
This is my action method:
[HttpPost]
public IActionResult Upsert(Category category)
{
ViewBag.Name = category.CategoryName;
ViewBag.ID = category.CategoryID;
return View();
}
And the data will pass to the Upsert action method successfully.
Question: How to pass data in jquery/ajax? For that I need to have a link like this :
<a href="/Admin/Category/Upsert/@item.CategoryID" >Edit</a>
and I really can't use Tag-Helpers in jquery.I can only pass CategoryID in jquery/ajax and do not know how to pass another field CategoryName and finally pass a Category object to my Upsert action method? In bellow, I get my data calling GetAll method ( so type: "GET" ) and render data in a table and create an Edit button for each row, I want to pass a complete object to Upsert method ( so type: "POST") ? I can make a variable in my each loop but out of the loop it is undefined !
$.ajax({
url: "/Admin/Category/GetAll",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += `
<tr>
<td>${item.categoryID}</td>
<td>${item.categoryName}</td>
<td> <div class="text-center">
<a href="/Admin/Category/Upsert/${item.categoryID}" class="btn btn-success">Edit</a>
<a class="btn btn-danger">Delete</a>
</div>
</td>
</tr>
` ;
console.log(item);
});
console.log(result);
$('#tblData tbody').html(html);
},
});
Upvotes: 0
Views: 2354
Reputation: 12705
Two points you should know:
1.The link is a Get request, so you should change [HttpPost]
on Upsert method to [HttpGet]
.
2.asp-route-*
generates the query string not the route value in the url ,if you want to generate a link in success function of ajax and click it to send a Category object Upsert method, change the code like below:
$.each(result, function (key, item) {
html += `
<tr>
<td>${item.categoryID}</td>
<td>${item.categoryName}</td>
<td> <div class="text-center">
<a href="/Admin/Category/Upsert?CategoryID=${item.categoryID}&CategoryName=${item.categoryName}" class="btn btn-success">Edit</a>
<a class="btn btn-danger">Delete</a>
</div>
</td>
</tr>
` ;
console.log(item);
});
Result
Upvotes: 3