I have a view controller that is returning ViewComponent
which returns a View (.cshtml) containing everthing I need.
In another view I want to use that, so i make ajax call to the controller to get raw html in the response.
Modal
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data
dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS:
$.ajax({
url: 'getModal/blabla',
type: 'GET',
data: {
Id: id
},
success: function (data) {
$('#myModal').modal('show').html(data);
},
error: function (error) {
console.error(error);
},
});
In my ViewComponent I return View like this:
return View("~/Views/MyModal.cshtml", new MyViewModel()
{
Id = obj.id
});
Here is a demo:
TestViewComponent.cshtml(you want to pass data to controller,so you need to use
type: 'POST'
in ajax):Controller:
ViewComponents/Sample1:
Views/Shared/Default.cshtml:
result:
You can also use partial view:
Controller:
View: