passing parameters <button type="button"> from view to controller - asp.net-mvc

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/

Related

ASP.NET Core MVC - Opening a Bootstrap modal view using a hyperlink

I am creating an ASP.NET (version 5) Core MVC application where I have a list of items. I try to make it so that when you click on an item it opens a (Bootstrap) modal view with the item's details (from another view). However, it seems like a hyperlink doesn't open the modal but instead opens the page itself (so not inside the modal). I got it working with a button, but I would like to make the user click on an item itself instead of a button.
This is the list item that I would like the user to be able to click on (the button is for testing):
I have the following page:
#model DetailsPatientFileViewModel
#section Scripts {
<script type="text/javascript">
$("#addBtn").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
$("#detailCard").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
</script>
}
<div class="patient-file-details-container">
<div class="title-container">
<h4>Treatments</h4>
<!-- This works just fine: -->
<button class=" btn-primary btn-primary" asp-controller="Treatment" asp-action="Create" asp-route-patientId="#Model.PatientId" data-toggle="ajax-modal" data-target="add-treatment" id="addBtn">Add</button>
</div>
<div id="component">
<!-- My list view component: -->
#await Component.InvokeAsync("TreatmentList", new { patientFileId = #Model.PatientFile.Id })
</div>
<!-- My modal: -->
<div id="Modal" class="modal fade">
</div>
</div>
The list view component (I also tested it with a button, see comment):
<ul class="card-list">
#foreach (var treatment in Model)
{
<li class="list-item-card">
<!-- Doesn't work: -->
<a asp-controller="Treatment" asp-action="Details" asp-route-id="#treatment.Id" data-toggle="ajax-modal" data-target="Modal" id="detailCard">
<h5>#treatment.Type</h5>
<p>#treatment.Date</p>
<p>#treatment.Employee.FirstName #treatment.Employee.LastName</p>
</a>
<!-- Does work: -->
<button asp-controller="Treatment" asp-action="Details" asp-route-id="#treatment.Id" data-toggle="ajax-modal" data-target="Modal" id="detailCard">Details</button>
</li>
}
</ul>
And finally the Details.cshtml (the to be opened view in the modal):
#using Core.Domain
#model Treatment
#{
Layout = null;
}
<h3>#Model.Type</h3>
<div class="modal-diaglog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="detailTreatmentLabel">Treatment details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>#Model.Date</p>
<p>#Model.Description</p>
<p>#Model.Employee.FirstName #Model.Employee.LastName</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
Does anyone know if it is possible to open a seperate view in a modal using a hyperlink? And if not, would there be a workaround to still be able to click on the list item itself?
Thank you in advance!
You can try to call a js function when click hyperlink:
ViewComponent:
<ul class="card-list">
#foreach (var treatment in Model)
{
<li class="list-item-card">
<!-- Doesn't work: -->
<a href="javascript:Details(#treatment.Id)">
<h5>#treatment.Type</h5>
<p>#treatment.Date</p>
<p>#treatment.Employee.FirstName #treatment.Employee.LastName</p>
</a>
<!-- Does work: -->
<button asp-controller="Treatment" asp-action="Details" asp-route-id="#treatment.Id" data-toggle="ajax-modal" data-target="Modal" id="detailCard">Details</button>
</li>
}
</ul>
page js:
#section Scripts {
<script type="text/javascript">
function Details(id) {
$.ajax({
type: "GET",
url: "Treatment/Details?id="+id,
success: function (res) {
$("#Modal").html(res);
$("#Modal").modal();
}
});
}
$("#addBtn").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
$("#detailCard").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
</script>
}

Best practice to show search result in a popup modal in ASP.NET MVC Core

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:

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>

How to passing form params from formRemote to remoteFunction in GSP

example is very simple.
select the two search condition and return a table with pagination, the whole page will not refresh.
so i use the grails formRemote to submit the form, and the control return the gender with template and it work well. However, the pagination i want to use Jquery, but i cant pass the formRemote params to the remoteFunction using onSuccess method in formRemote.
Here it is the code:
<div class="formSep col-md-12">
<g:formRemote update="searchResult" class="form-inline" role="form" name="form"
url="[controller: 'autoRateRecord', action: 'search']" onSuccess="initPagination(data)">
<div class="form-group col-lg-2">
<g:select class="form-control" name="notified" from="${['done', 'undone']}"
noSelection="${['null': 'Oops']}">
</g:select>
</div>
<div class="form-group col-lg-2 pull-right">
<button type="submit" class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-search"></span> search
</button>
</div>
</g:formRemote>
</div>
<div id="searchResult">
<g:render template="searchList"/>
</div>
<script type='text/javascript'>
function initPagination(data) {
console.log("------> " + data)
$("#Pagination").pagination(10, {
callback: getRecordList(1),
prev_text: "prev",
next_text: "next",
items_per_page: 15,
num_edge_entries: 1
});
}
**!!!!!!! need formRemote data !!!!!!!**
function getRecordList(page_index) {
<g:remoteFunction controller="autoRateRecord" action="search" update="searchResult" params="'page='+page_index"/>
}
// On load, style typical form elements
$(function () {
});
</script>
the controller code is:
def search = {
log.info(ToStringBuilder.reflectionToString(params))
// logic .....
render(template: "searchList", model: [
autoRateRecords: result,
total : result.totalCount
])
}
I would change the pagination script to something like
$("#pageHiddenFieldId").val(pageNo);
$("#myForm").submit();

jquery ui tab select method not working

I have two tabs with a submit button on each tab. When the button is clicked, I need to reload the content of that specific tab to get updated data from the server.
if (validStatus()) {
$.ajax({
//...
success: reloadTab
});
}
function reloadTab() {
var currentTab = $("#tabs").tabs("option", "active");
alert(currentTab);
$('#tabs').tabs('select', currentTab);
alert(currentTab);
}
When the button is clicked, the tab doesn't refresh. I see the first alert but not the second.
HTML is as follows:
Head:
<link rel="stylesheet" href="#this.Url.Content("//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css")" />
<script>
$(function () {
$("#tabs").tabs();
});
</script>
Body:
<div id="tabs">
<ul>
<li>The first tab</li>
<li>the second tab</li>
<li>Success</li>
</ul>
<div id="Success">
testing
</div>
<div id="Tab1">
<fieldset >
<legend>Overview</legend>
<input type="button" id="submit1" value="submit" />
<br />
</fieldset>
<fieldset style="width: 700px;">
<legend>Overview</legend>
<div>
<table >
//updated with ajax
</table>
</div>
</fieldset>
<script>
//reloadTab is in here
</script>
</div>
<div id="Tab2">
<fieldset style="float:left; width:300px;">
<input id="submit2" type="button" value="submit"/>
</fieldset>
<fieldset style="float:left;">
<legend>Overview</legend>
<table>
//updated with ajax
</table>
</fieldset>
<script>.....</script>
</div>
Turns out tabs.('select', ...) is deprecated, using tabs.('option', 'active', index) fixed my issue. Solution found in this comment: https://stackoverflow.com/a/16033969/1463649
Do you see anything in the console of your browser? What browser are you using?
Try this to help you with the debugging.
function reloadTab() {
console.log($('#tabs')); // if this is an empty object, the element doesn't exist when you call this function
console.log($('#tabs').tabs()); // if this doesn't return 'function', you haven't included a library properly, maybe jquery ui, or jquery, or you're using an old version or something
console.log(currentTab); // if this is undefined then something went wrong and no tab is active
var currentTab = $("#tabs").tabs("option", "active");
alert(currentTab);
$('#tabs').tabs('select', currentTab);
alert(currentTab);
}

Resources