I have a method in my MVC controller, that when invoked downloads a document.
I have a bootstrap Modal, where the href resides which points to this method.
#Html.ActionLink("Download", "Download", new { applicantId = 1, templateId = 1 })
The applicantId and templateId for the minute are hardcoded, but these values are passed to the Modal via jquery as text values.
Is it possible to get a HTML id dynamically and add it to the #Html.ActionLink?
Modal:
<div id="template1">
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<h3 id="app" style="display:none"></h3>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Letter Template Logo</h4>
</div>
<div class="modal-body">
<img style="background-size:cover;" src="~/Content/images/image.png" alt="" />
</div>
<div class="modal-footer">
ActionLink("Download", "Download", new { applicantId = 1, templateId = 1 })
</div>
</div>
</div>
</div>
</div>
I have created .NetFiddle. It works here
You can change Html.ActionLink() method parameters with .replace() method and you can implement like following.
//html
Parameter 1:<input id="param1" />
Parameter 2:<input id="param2" />
<div class="modal-footer">
#Html.ActionLink("Download", "Example", new { applicantId = 1, templateId = 1 })
</div>
<button id="yourbutton">Change Action Link</button>
//jquery
<script type="text/javascript">
$("#yourbutton").on("click",function(){
var param1 = $("#param1").val();
var param2 = $("#param2").val();
console.log(param1);
console.log(param2);
var link = '#Html.ActionLink("Download", "Example",
new { applicantId = "_applicantId_", templateId = "_templateId_"})';
if(param1 == "" || param2 == "")
{
alert("please fill all parameter inputs")
}
else
{
link = link.replace('_applicantId_', param1);
link = link.replace('_templateId_', param2);
$(".modal-footer").html(link)
alert("I have changed ActionLink. Please click the download link")
}
})
</script>
#Html.ActionLink("Pond", "Pond", "Home", htmlAttributes: new {
#class="classNameYouWantToAdd" })
or
#Html.ActionLink("Pond", "Pond", "Home", new {
#class="classNameYouWantToAdd" })
if you want to do it from JQuery then you can either target the li tag that contains the link or Add a class name to the your action link like above and then update the class of the object as your normally would.
$('.TargetedClassNameOfActionLink').addClass('addDifferentClass').removeClass('removeSomeOtherClass')
$('#liTagId').find('.ClassNameOfActionLink').addClass('addDifferentClass').removeClass('removeSomeOtherClass')
or
$('#tabPond').addClass("greenTab");
Related
I have a list of products and you want to display a modal window to edit the parameters of these products
for this you have in each row a button that calls the modal ....
my Edit button in Index.cshtml:
<td>
Editar
</td>
my script in Index.cshtml:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$("#EditModalBody").load(url, function () {
$("#myModalEditar").modal("show");
})
}
</script>
my modal Bootstrap in Index view:
<div class="modal fade" id="myModalEditar">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Editar Producto</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="EditModalBody">
</div>
</div>
</div>
</div>
my ActionResult in controller:
public ActionResult EditarProducto (int Kn_CodigoProducto)
{
Producto model = new Producto();
if(Kn_CodigoProducto >= 0)
{
var producto = db.Productoes.Where(c => c.Kn_CodigoProducto == Kn_CodigoProducto).FirstOrDefault();
model.v_Nombre = producto.v_Nombre;
}
return PartialView("_PartialEditar", model);
}
and my partial view that receives the model sent from the controller:
#model Dominio.Producto
<div class="jumbotron">
<label>Esto es una prueba #Model.v_Nombre</label>
</div>
I have the partial view inside the folder along with the Index.cshtml view
Also I have referenced the corresponding scripts, what is happening? What is missing? It is the first time that I work with partial and modal views ... am I doing it correctly?
Expected behavior: when you click on the edit button, the modal opens
Behavior obtained: although when clicking on the edit button it enters the action of my controller, it does not show the modal
any help for me?
Instead of this:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$("#EditModalBody").load(url, function () {
$("#myModalEditar").modal("show");
})
}
</script>
Can you try this:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$.ajax({
url: url,
type: 'GET',
success: function (result) {
$('#EditModalBody').html(result);
$("#myModalEditar").modal("show");
},
error: function (xhr, status) {
alert(status);
}
});
}
</script>
You don't need to write jquery to invoke modal popup, instead you can use data-toggle and data-target attribuites.
Editar
I have an issue where I'm attempting to use a URL to open a Modal in window B, by clicking on an image link in window A. The image itself is setup inside an anchor tag, such that <a href="myserver.mydestinationB.com#myModal><img src='myImage'></a> is in window A.
How can I get to window B AND open the modal only using the URL, if possible.
Code :
Page A
<a href="http://www.x.com/#DesiredModalID">
<img typeof="foaf:Image" src="http://google.com/image.png" width="1920" height="1080" alt="">
</a>
Page B
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog"><!-- Modal content-->
<div class="modal-content">
<div class="modal-header"><button id="modalclose" class="close" data- dismiss="modal" type="button">×</button>
<h4 class="modal-title" id="header-data">Modal Header</h4>
</div>
<div class="modal-body">
<p id="modal-text">Some text in the modal.</p>
<div id="modal-body" style="text-align: center;"> </div>
</div>
<div class="modal-footer">
<h5 id="footer-data" style="font-weight:bold;font-style:italic;float:left;">Test Data</h5>
<button class="btn btn-default" data-dismiss="modal" id="closetwo" type="button">Close</button></div>
</div>
</div>
<img id="myimage" src='myImage'>
<script>
$(document).ready(function(){
$("#myimage").click(function() {
$("#myModal").modal();
})
})
</script>
<a href="myserver.mydestinationB.com?mymodal=open>
--- On Page B you add script ---
<script>
$(document).ready(function(){
var mymodal = $_GET('mymodal');
if(mymodal != null){
$("#myModal").modal();
}
})
function $_GET(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
</script>
I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.
Can someone help?
This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" 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">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</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">Save</button>
</div>
</div>
</div>
</div>
I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.
What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.
I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.
Bootply Sample
And if needed... How to specify data attributes in razor
First of all
you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:
<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>
Then
In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
For each information you want to show, you create an input referencing the current loop values.
Now you finally show the modal
Your document.ready function will have this new function:
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
It simply grab those values we placed in hidden inputs.
Your final code
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" 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">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</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">Save</button>
</div>
</div>
</div>
I have an Index View and when I click the Edit button, I post to the Edit View (via the Controller) and display a bootstrap modal popup.
By posting to the Edit View, the Controller/View automatically handle getting and displaying the correct data on the modal popup.
Once I'm on my Edit View with the dialog box appearing and I click on the Close button, I simply want to link back to the Index page again; but instead, am getting an error with the path of the url. The new path I want to link to is being "tacked on" to the original path instead of replacing it.
I'm using the Url.Action method inside the click event of the Close button (of which I verified it's hitting) and have verified the location.href url is exactly what is in the url variable as you see in the code.
What do I need to do to correctly link back to the Index url?
Index View
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>Edit
Edit Controller
// GET: Categories/Edit/5
public async Task<ActionResult> Edit(short id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = await db.GetCategoryIDAsync(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
Edit View
#model YeagerTechDB.Models.Category
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="modal" id="categoryEditModal" tabindex="-1" role="dialog" aria-labelledby="categoryModal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="categoryModal-label">Category Description</h4>
</div>
<div class="modal-body">
<div class="form-group">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CategoryDescription, new { #class = "control-label required col-offset-1 col-lg-3 col-md-3 col-sm-3 col-xs-3" })
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
#Html.EditorFor(model => model.CategoryDescription, new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.CategoryDescription, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="btnCloseCategory">Close</button>
<button type="submit" class="btn btn-primary" id="btnSaveCategory">Save</button>
</div>
</div>
</div>
</div>
<div>
#Html.Hidden("categoryEditUrl", Url.Action("Edit", "Category", new { area = "Categories" }))
#Html.Hidden("catID", Model.CategoryID)
</div>
#section Scripts {
<script>
$(document).ready(function ()
{
if (typeof contentEditCategory == "function")
contentEditCategory()
});
</script>
}
JS for Edit View
$('#btnCloseCategory').click(function (e)
{
var url = '#Url.Action("Index", "Category", new { area = "Categories" })';
location.href = url;
return false;
});
Image of modal popup
Image of error
Assuming your javascript is in an external file you could do the following:
Attach the url to your button within your view with a data attribute as follows:
<button type="submit" class="btn btn-default" id="btnCloseCategory"
data-url="#Url.Action("Index", "Category", new { area = "Categories" })">Close</button>
Then pull back the url with the data method as follows:
$('#btnCloseCategory').click(function (e)
{
var url = $(this).data('url');
location.href = url;
return false;
});
Try changing type="submit" to type="button" for your Close button.
<button type="button" class="btn btn-default" id="btnCloseCategory">Close</button>
I have an MVC 4 application containing a grid with a link button to trigger the display of record details. I'm using a bootstrap modal dialog to display record details when the user selects a grid row.
I don't want to load the record details unless they are asked for; there are too many data elements involved (1000+).
The grid page uses a modal div containing the partial page (with a ViewModel reference).
I need the partial page's ViewModel to refresh prior to the display of the dialog. so when the user clicks the link, I get the record id from the grid and use it to create the url to the controller method - which seems to work, but seems to happen AFTER the dialog is shown.
How do I get this to work?
This code is in my Index.cshtml:
×
Account Number: #Html.DisplayFor(model => model.AccountNumber)
#{Html.RenderPartial("_KeyTable");}
#{Html.RenderPartial("_LoanTable");}
Close
$(document).ready(function () {
$("#divDialog").hide();
$("#btnClose").hide();
$("#lblAcceptAll").show();
$("#OnHoldsGrid").focus();
pageGrids.OnHoldsGrid.onRowSelect(function (e) {
accountNumber = e.row.AccountNumber;
});
$(".modal-link").click(function (event) {
event.preventDefault();
$('#detailsModal').removeData("modal");
var url = '#(Url.Action("_DetailsForModal", "Home", null, Request.Url.Scheme))?accountNumber=' + accountNumber;
$('#detailsModal').load(url);
$('#detailsModal').modal('show');
//alert(url);
});
});
// This code is in my Controller:
public ActionResult _DetailsForModal(string accountNumber)
{ // This refreshes the data in the ViewModel:
LOIHoldsViewModel model = new LOIHoldsViewModel();
model.GetLOIHoldExtended(accountNumber);
return PartialView("_DetailsForModal", model);
}
// This code is in my partial page _KeyTable.cshtml:
#model LOIHolds.Models.LOIHoldsViewModel
<div id="divKeyTable">
<br />
<hr />
<div class="KeyTableExpandContent">
<h2>Show/Hide Key Table Information</h2>
</div>
<label>Provider Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.ProviderDate)
<label>PFI Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.PFIDate)
<label>User Accept Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.UserAcceptDate)
<label>User Deny Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.UserDenyDate)
<label>Process Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.ProcessDate)
<label>Fiserv Accept Date:</label>
#Html.DisplayFor(model => model.LOIHoldWithTables.KeyTable.FiservAcceptDate)
</div>
<script>
$('.KeyTableExpandContent').click(function () {
$('.divKeyTable').toggle();
});
</script>
// This is the partial _DetailsForModal.cshtml:
#model LOIHolds.Models.LOIHoldsViewModel
<div class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="detailsModalLabel"><label>Account Number: </label>#Html.DisplayFor(model => model.AccountNumber) </h4>
</div>
<div class="modal-body">
<p>
#{Html.RenderPartial("_KeyTable");}
#{Html.RenderPartial("_LoanTable");}
</p>
</div>
<div class="modal-footer">
<button type="button" id="CancelModal" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
You will have to use Ajax when you click the .modal-link:
$(".modal-link").click(function (event) {
var mUrl = '#(Url.Action("DetailsForModal", "Home", null, Request.Url.Scheme))?accountNumber=' + accountNumber;
$.ajax({
url: mUrl,
success:function(result){
// result should contain PartialView from Controller
//Assign Modal DIV the PartialView
$('#detailsModal').html(result);
$('#detailsModal').modal('show');
}
});
}
Put your Modal Logic in a Partial View, then Create a function in Home Controller: Something like this:
public ActionResult DetailsForModal(int accountNumber){
var model = new PartialModalDialogViewModel();
// Load Modal Data
return PartialView("PartialViewName", model);
}
EDIT:
Try removing this from the Modal Partial View and put in somewhere in the _Layout.cshtml
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel" aria-hidden="true">
</div>