Reputation: 316
I have a Data table with in a MVC view and this data tables each record has edit button in it.
When the edit button is clicked, I need to pass the Id of the record to the MVC action method and load the MVC view for edit form from MVC action.
This is my JQuery Data table code.
function PopulateQueryGrid(data) {
$('#querytable').dataTable({
destroy: true,
data: data,
columns: [
{ "data": "type", "name": "Product Type", "autoWidth": true },
{
"data": "isDeleted",
"render": function(data, type, full) {
if (full.isDeleted !== true) {
return "<div style='background-color:PaleGreen;width:100px;text-align:center;padding:2px'> Active </div>";
} else {
return "<div style='background-color:orange;width:100px;text-align:center;padding:2px'> Deleted </div>";
}
}
},
{
"data": "id",
"render": function(data, type, full) {
**// 1 does not work
//return '<input type="button" value="Edit" class="btn btn-info" onclick=\'editItem(' + JSON.stringify(full) + ')\' />';
// 2 does not work
//return '<form asp-controller="ProductType" asp-action="EditProductType" method="get"><input type="hidden" name="typeId" id="typeId" value="' +
//full.id +
//'" /><input type="submit" class="btn btn-info" value="Edit" /></form>';**
}
},
{
"data": "ID",
"render": function(data, type, full) {
return '<input type="button" value="Delete" class="btn btn-danger" onclick=\'deleteItem(' +
JSON.stringify(full) +
')\' />';
}
}
]
});
}
function editItem(item) {
$.ajax({
url: '/ProductType/EditProductType',
data: { typeId : item.id },
type: 'GET',
contentType: 'application/json; charset=utf-8',
error: function() {
alert("error");
}
});
}
function deleteItem(item) {
alert("delete : " + item.id);
}
And this is the MVC action that I need to call once the Edit button is clicked.
public async Task<IActionResult> EditProductType(int typeId)
{
try
{
var productType = await _productTypesService.GetProductTypeByIdAsync(typeId);
return View(productType);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Below is the HTTP Post version of the same action method.
[HttpPost]
public IActionResult EditProductType(ProductTypeViewModel vm)
{
try
{
if (ModelState.IsValid)
{
_productTypesService.EditProductTypeAsync(vm);
return RedirectToAction("Index");
}
return RedirectToAction("EditProductType", vm);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
I tried 2 ways to achieve this so far (both are commented in the above Data Table Code), but non of them worked.
Question - how to pass values to MVC controller action from JS Data table button click, and load a MVC view (form) from that action?
Appreciate a lot your help. Thank you.
Upvotes: 0
Views: 1464
Reputation: 316
Thanks for the suggestion/comments. As suggested on comments, I got it to work using a <a>
tag.
{
"data": "id",
"render": function(data, type, full) {
return '<a class="btn btn-info" href="/ProductType/EditProductType?typeId=' + full.id + '">Edit</a>';
}
},
Upvotes: 0