Best practice to show search result in a popup modal in ASP.NET MVC Core - asp.net-mvc

I am passing a value (search string) from a form to a controller action method where I perform some activities to find specific records from the db then passing the result to either ViewBag or to a model in order to display the result in a view.
The easy way is to pass the result as a model (or viewmodel) to the view .. something like:
1- Pass the string from a form to the controller.
2- in the controller, method, after performing the search and saving it to a list/var ..
return View(mymodel);
3- in the view .. we can say
#foreach (var item in Model)
{
... table here to display the columns and the data..etc.
}
The question is, in stead of the view, how can I display the result in a modal popup ?
There are so many suggestions with many different JQuery or JavaScripts but is there any easier solution?
is there anything like (simply) show me the view in a popup modal ?
Thanks in advance

is there anything like (simply) show me the view in a popup modal ?
I think the simpest way to display the result in a modal popup is using partial view and ajax.
Here, you cannot avoid creating a view to store the content that needs to be displayed in the modal popup. Of course, you only need to create a partial view instead of a view.
Here is a simple demo for your reference:
main view:
Update:
#{
ViewData["Title"] = "Testpop";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Testpop</h1>
<form>
<input id="Text1" type="text" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" id="showPop">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- 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 ">
<div id="popup">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="submitModal">Submit</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
#section Scripts{
<script>
$('#showPop').click(function () {
var url = '#Url.Action("GetPartialView", "Default")';
$.ajax({
url: url,
type: 'post',
data: { "para": $("#Text1").val()},
success: function (data) {
$('#popup').html(data);
}
});
})
$('#submitModal').click(function () {
var url = '#Url.Action("GetData", "Default")';
$.ajax({
url: url,
type: 'post',
data: { "data": $("input[name='data']").val() },
success: function () {
$("#Text1").val("");
alert("pass successfully!");
}
});
});
</script>
}
Default/GetPartialView action:
[HttpPost]
public IActionResult GetPartialView(string para)
{
//get data
var model = _context.Person.Where(x=>x.Name == para).ToList();
return PartialView("_PopView",model);
}
_PopView.cshtml partial view:
#model IEnumerable<Person>
<table class="table table-bordered">
<tr>
<td>Id</td>
<td>Name</td>
<td>Nome_Tipo</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#item.Id
</td>
<td>
#item.Name
</td>
<td>
#item.Nome_Tipo
</td>
</tr>
}
</table>
<input id="data" type="text" name="data" />
pop up submit data to the action:
[HttpPost]
public IActionResult GetData(string data)
{
//do anything.
return Ok();
}
Here is the new result:

Related

How do I access query data in modal popup

This seems like it should be simple but nothing is in ASP.NET Core MVC. I would simply like to present the results of a query in a table inside a modal popup. The modal is opening but the table is empty. Not just that but the table is getting created before I even click the button to show the modal. I'm hoping some kind person out there can help me.
This is the controller action method:
public async Task<IActionResult> GetStudies(int id)
{
var results2 = (from s in _context.Studies
join sn in _context.StudyNodes on s.Id equals sn.StudyId
where sn.NodeId == id
select new BundleNodeViewModel
{
StudyId = s.Id,
StudyName = s.Name
}).ToList();
return Ok(results2);
}
This is the function calling the action:
getStudies = (url, id) => {
$.ajax({
type: 'GET',
url: url,
data: {
'id': id
},
success: function (res) {
console.log(res);
$("#formModal").find(".modal-body").html(res.Name);
$("#formModal").find(".modal-title");
$("#formModal").modal('show');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
console.log(response);
alert("error");
}
})
};
And this is the modal popup:
<div id="formModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="close_" style="background-color:transparent; color:aquamarine; border-style:none">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Assigned Studies</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-md-4">
<form asp-action="Bind" asp-controller="Studies">
<div class="form-group">
<table class="table table-hover" style="height: 300px">
<thead>
<tr class="position-sticky" style="color:aliceblue; background-color:#126E75">
<th class="text-start">
Study
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class=" table-light">
<td class="text-start">
#item.StudyName
</td>
</tr>
}
</tbody>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" id="btnClosePopup" value="Close" data-dismiss="modal" class="btn btn-danger" />
</div>
</div>
</div>
</div>
I'm really confused about the order in which things are happening. For some reason the code in the modal runs when the parent page is loaded and not when you click the button on the parent page to open the modal. So the model in the foreach() statement is not the model I need it to be. When I click on the open modal button I expect it to go to the controller, get the data and return it to the modal where I can loop through the object and create a table.
Any ideas anyone?
I didn't understand your question but I have tried to do what you might want to do.
we have created dummy data which should you get from the ajax.
If you don not want to open the modal on page load please remove the Document Ready part.
try to place the 'getStudies' function body to your ajax's success block.
$(document).ready(()=>{
getStudies();
});
var data = [
{ 'StudyId': 1,'Name':"STD 10"},
{'StudyId' : 2,'Name':"STD 11"}
];
let getStudies = (url, id) => {
$("#formModal").find("tbody").html('');
$.each(data,(index,val) =>
{
let tr=`<tr class="table-light"><td class="text-start">${val.Name}</td></tr>`;
$("#formModal").find("tbody").append(tr);
});
$("#formModal").modal('show');
};
<html>
<head>
<title>kaushal</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body> <button onClick="getStudies()">open modal</button>
<div id="formModal" style="width:100%;border:1px solid red;" class="modal fade in" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="close_" style="background-color:transparent; color:aquamarine; border-style:none">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Assigned Studies</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-md-4">
<form asp-action="Bind" asp-controller="Studies">
<div class="form-group">
<table class="table table-hover" style="height: 300px">
<thead>
<tr class="position-sticky" style="color:aliceblue; background-color:#126E75">
<th class="text-start">
Study
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" id="btnClosePopup" value="Close" data-dismiss="modal" class="btn btn-danger" />
</div>
</div>
</div>
</div>
</body>
</html>

How to pass an id of an item with a button from a list of items to a modal, then from modal to a controller?

So I have a list of web urls, all fetched from SQL and has an id, an address etc.
I list them in a table using the following:
<div>
<div class="well" margin-left:20px; margin-right:20px">
<h2 style="margin-left:20px; margin-top:10px">Control Added Links</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>
Link Address
</th>
<th>
Check Interval
</th>
<th>
Status
</th>
<th>
#
</th>
</tr>
</thead>
<tbody>
#foreach (var i in links)
{
<tr>
<td>
#i.Address
</td>
<td>
#i.Interval
</td>
<td>
#if (i.Status)
{ <text> ON </text>}
else
{ <text> OFF </text>}
</td>
<td>
<a href="~/Control/Delete/#i.Id">
✖
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
"links" here is a list of Link models:
#{
var links = (List<Link>)ViewData["LinkInfos"];
}
Right now, there is an X button you can click to delete a link from database, by using i.Id of the item 'i'. What I want to do is, ask for a confirmation with a modal, instead of directly deleting.
I delete the link with a function inside controller using the follownig:
public ActionResult Delete(int Id)
{
UserLinks links = new UserLinks();
links.delete(Id, User.Identity.Name);
return RedirectToAction("Index");
}
I changed this code, managed to pass the data from button to modal:
<a data-toggle="modal" data-id="#i.Id" data-request-url="#Url.Action("Delete", "Control")" title="Delete link" class="delete-Link btn btn-danger" href="#deleteLink">
✖
</a>
<div id="deleteLink" class="modal fade" 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">Test</h4>
</div>
<div class="modal-body">
This will delete all records related to this link. Are you sure?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="deleteConfirm()">Yes</button>
<button class="btn btn-warning" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<script>
var myLinkId
var url
$(document).on("click", ".delete-Link", function () {
myLinkId = $(this).data('id');
url = $(this).data('request-url');
$(".modal-body #linkId").val(myLinkId);
// As pointed out in comments,
// it is superfluous to have to manually call the modal.
// $('#addBookDialog').modal('show');
});
function deleteConfirm()
{
debugger;
$.post(url), { Id: myLinkId };
}
</script>
But problem right now is passing this data from modal to controller. I wrote the "deleteConfirm" function but it doesn't seem to work, it doesn't go to ~/Control/Delete.
First part of my question is actually solved, I can pass id from button to modal, but I am not sure if it is properly solved so I am asking for that too, I currently pass the id using JavaScript but wonder if I can directly pass from button to modal itself.
I managed to fix my issue and properly delete by creating a modal for each item... which I assume is the sloppy way and can be a problem when I have like, let's say 100 links.
One solution I have in mind but don't know how to implement:
Have a "globalId" parameter inside view, when a button is clicked, i.Id is assigned to globalId, then open the modal, which has globalId as a parameter inside. Just like with , use inside modal, which changes by deletion button you click. But problem is, don't know how to create this global parameter and assign i.Id to it with click of a button.
A way I think I can implement my possible solution:
I want to have a variable in a view, let's say int globalId.
Let's say I press the delete button for id = 10, what I want to happen is simply have "global = id" so I want to assign 10 to number. If id of button is 12, I want "global = id" to happen again, this time to assign 12 to number.
So this way, modal will just use globalId, so I can make it have:
Yes
This way, there will only be one modal, every button will open the same modal and modal will use the same variable. Just value for globalId assigned to this modal will change with click of a button.
Question is, how can I create this local variable and how can I simply assign a new value to this local variable?
I have made some changes in your view which make this possible to work. I have added one hidden field in model and store the id on show event of the model. And on confirm id is get from this hidden field to construct the post url.
<a data-toggle="modal" data-id="#id" data-request-url="#Url.Action("Delete", "Home")" title="Delete link" class="delete-Link btn btn-danger" href="#deleteLink">
✖
</a>
<div id="deleteLink" class="modal fade" role="dialog">
<div class="modal-dialog">
<input type="hidden" id="linkId" />
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Test</h4>
</div>
<div class="modal-body">
This will delete all records related to this link. Are you sure?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="deleteConfirm()">Yes</button>
<button class="btn btn-warning" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<script>
$('#deleteLink').on('show.bs.modal', function (e) {
$("#linkId").val($(e.relatedTarget).data('id'));
});
function deleteConfirm()
{
var url = "#Url.Action("Delete", "Control")/" + $("#linkId").val();
$.post(url).success(function () {
location.href = "#Url.Action("Index", "Control")";
});
}
</script>

passing data to modal dialog from controller to partial view with viewmodel MVC Ajax

I want to pass data to modal dialog from my controller to partial view using view model but it isn't working.
When I tried passing data to my view model without modal dialog and it's fine for the result
I have put debug points and showing the value in my view model return to my partial view but it isn't displaying anything.
Code in my View
<div class="col-sm-btn">
<button type="button" id="btnSearchType" class="btn bg">
<i class="material-icons">search</i>
</button>
</div>
#Html.Partial("~/Views/Dialog/Type.cshtml");
<script>
$("#btnSearchType").click(function () {
$.ajax({
type: "GET",
url: '#Url.Action("ListType", "MasterMaterial")',
data: {
category: $("#txtCategory").val()
},
dataType: "html",
success: function (response) {
$('#type').modal('show');
},
error: function (response) {
alert("error");
}
});
});
Code in my Partial View
#model List<MVC_Client.Models.MasterType>
<div class="modal fade" id="type" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="defaultModalLabel">Type</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table id="listType" class="js-basic-example dataTable">
<thead>
<tr>
<th>Type Code</th>
<th>Type Namce</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var type in Model)
{
<tr>
<td>#type.TypeCode</td>
<td>#type.TypeName</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Code in my Controller
[HttpGet]
public ActionResult ListType(string category)
{
MasterTypeClient mtc = new MasterTypeClient();
List<MasterType> listType = new List<MasterType>();
listType = mtc.GetListTypes(category).ToList();
return PartialView("~/views/DialogPages/Type.cshtml", listType);
}
Code in my Model Client
public IEnumerable<MasterType> GetListTypes(string category)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("MasterType/Category/" + (category)).Result;
if (response.IsSuccessStatusCode)
return response.Content.ReadAsAsync<IEnumerable<MasterType>>().Result;
return null;
}
Code in my Model
public class MasterType
{
public string TypeCode { get; set; }
public string TypeName { get; set; }
}
And here is for the result
Result for my modal dialog
You're loading your PartialView when the View loads. It looks like you want to only show the modal PartialView after search is clicked.
I would go ahead and put the modal structure in the View and change the PartialView to just generate the table. Something like:
View
<div class="col-sm-btn">
<button type="button" id="btnSearchType" class="btn bg">
<i class="material-icons">search</i>
</button>
</div>
<div class="modal fade" id="type" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="defaultModalLabel">Type</h4>
</div>
<div class="modal-body table-placeholder">
</div>
</div>
</div>
</div>
<script>
$("#btnSearchType").click(function () {
$.ajax({
type: "GET",
url: '#Url.Action("ListType", "MasterMaterial")',
data: {
category: $("#txtCategory").val()
},
dataType: "html",
success: function (response) {
$('.table-placeholder').html(response);
$('#type').modal('show');
},
error: function (response) {
alert("error");
}
});
});
Partial View
#model List<MVC_Client.Models.MasterType>
<div class="table-responsive">
<table id="listType" class="js-basic-example dataTable">
<thead>
<tr>
<th>Type Code</th>
<th>Type Namce</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var type in Model)
{
<tr>
<td>#type.TypeCode</td>
<td>#type.TypeName</td>
</tr>
}
}
</tbody>
</table>
</div>

Boostrap Modal not working on ASP.NET MVC

I have readed a lot of blogs and articles about showing MVC partial views using Boostrap modals. It seems that I have exactly what I'm seen on the material consulted but still it doesn't show the modal. I just need to show the partial view with the Album details in a modal. The controller is working fine when I load the URL through the browser.
This is the Index HTML code where the modal is shown:
<tbody>
#foreach( var album in Model.Albums)
{
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
}
</tbody>
Partial View
<div class="modal fade" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="albumModalLabel">Album Details</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4">
<div class="row">
<label>Album<input class="form-control" type="text" id="title" /></label>
</div>
<div class="row">
<label>Artist <input class="form-control" type="text" id="artist" /></label>
</div>
<div class="row">
<label>Genre <input class="form-control" type="text" id="genre" /></label>
</div>
<div class="row">
<label>Year <input class="form-control" type="text" id="year" /></label>
</div>
</div>
<div class="col-md-8">
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Track</th>
<th>Song Title</th>
<th>Length</th>
</tr>
</thead>
<tbody class="tracks"></tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
HomeController
[HttpGet]
public ActionResult Album(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var albumInfo = _service.GetAlbumInfo((int) id);
if (albumInfo == null) return HttpNotFound();
return PartialView("_Album", albumInfo);
}
Script
$(document).ready(function() {
$('.list-element').click(function () {
debugger;
var $buttonClicked = $(this);
var url = $buttonClicked.attr('data-url');
$.get(url, function (data) {
$('#albumContainer').html(data);
$('#albumModal').modal('show');
});
});
});
In almost all of the SO questions counsulted, they wasn't using data-target but I am. What do I need to modify to achieve that the modal shows?
VIEW
#model ShowModal
<table>
<tbody>
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModal">
#Html.Partial("_albumPartial", Model)
</div>
CONTROLLER
[HttpGet]
public ActionResult Album(int? id)
{
ShowModal modal = new ShowModal();
var albumInfo = _service.GetAlbumInfo((int) id);
modal.Info1 = albumInfo.Info1;//and other fields
return PartialView("_albumPartial", modal);
}
SCRIPT
<script>
$(document).ready(function () {
$("#albumModal").on("show.bs.modal", function (e) {
var button = $(event.relatedTarget) // Button that triggered the modal
var url = button.data('url') // or button.attr("data-url") or get here just the id and create the URL here
$.get(url, function (data) {
$('#albumModal').html(data);
$('#albumModal').modal('show');
});
});
});
</script>

passing parameters <button type="button"> from view to controller

I have such a code view:
<section>
#foreach (var request in request_list)
{
<div style="display:inline">
<button class="checkbox checked" type="button" >#request.Message</button>
</div>
}
</section>
and javascript:
$('.checkbox').click(function () {
$(this).toggleClass('checked');
});
How do I get the controller if the class of the button checked?
you can use $.ajax
you find more information on http://api.jquery.com/jquery.ajax/

Resources