Inside a normal View, we are populating a table via the model with this:
@foreach (var item in Model)
{
if (item.PartnerSubscriptionID > 0)
{
<tr id='customlistid_@item.CustomList.ListID'>
<td>
<button type="button" class="btn btn-secondary" onclick='ListCustomEdit("@item.CustomList.ListID")'>
<i class='fas fa-users'></i>
</button>
</td>
<td style="display:none">@Html.DisplayFor(modelItem => item.CustomList.ListID)</td>
<td style="text-align:left">@Html.DisplayFor(modelItem => item.CustomList.ListName)</td>
<td><button id='btnDelete' type='button' class='btn btn-danger' onclick='ListCustomDeleteConfirm(" @item.CustomList.ListID ")'><i class='fas fa-trash'></i></button></td>
</tr>
}
}
On the same page I have a View Component. It works when I hard code the ListID like this:
<div class="col-8">
@await Component.InvokeAsync("ListCustomMembers" , new {ListID = 7 } )
</div>
But we need the ID to be passed in when the user clicks the row. Ie, where we currently have the onclick=ListCustomEdit()
we need to refresh the View Component
with the correct ID.
How do I do it?
ViewComponent
is rendered on the server side, so when the user clicks in the browser, you need to send another request to the server to render and return the ViewComponent
with the new parameter, for which you can use a controller
.
Create an action
in the controller
you want to return the ViewComponent
, then update the view as shown below after clicking the button using jquery
public class TestController : Controller
{
public IActionResult GetNewList(int listId)
{
return ViewComponent("ListCustomMembers", new { listId });
}
}
on the view side:
<button type="button" class="btn btn-secondary" onclick='ListCustomEdit("@item.CustomList.ListID")'>
<div class="col-8" id="ListCustomMembers">
@await Component.InvokeAsync("ListCustomMembers" , new {ListID = 7 } )
</div>
<script>
function ListCustomEdit(listId) {
$.get('/test/GetNewList/?listId=' + listId,
function(result) {
$("#ListCustomMembers").html(result);
});
}
</script>