How should i handle calling modal widow from controller under certain conditions - javascript

I am trying to create a modal window that will open under some conditions.
I did create a modal window that is opening on button click. What should i change?
My view:
<button type="button" data-toggle="modal" data-target="#popupModal">open</button>
<div id="popupModal"
class="modal hide fade"
tabindex="-1"
role="dialog"
aria-labelledby="popupModalLabel"
aria-hidden="true">
...some html
</div>
</div>
my controller:
if (some conditions)
{
//here i want to open my modal window somehow
}

You can check these conditions in the button click event,
$(button).click(function(){
if (some conditions)
{
$("#popupModal").modal("show");
//$("#popupModal").show();
}
});
I've created jsFiddle with an example for you: JsFIddle

From your controller Send your option in data array when you load your view.
for example, your code should be Something like this..
Controller:
$data = array();
if (some conditions)
{
$data['option1'] = 'modal1';
}
else{
$data['option2'] = 'modal2';
}
$this->load->view('your view file', $data);
View:
if($option1){
// modal 1 html
}
else{
// modal 2 html
}
Try this. i hope you get an idea.

Related

Using X.PagedList on a modal pop-up

I've got a modal pop up on a page:
...
<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="companySearchModal" aria-hidden="true" id="companySearchModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="companySearchModalContent"></div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
...
That I pop up:
...
$('#companySearchModalContent').html(data);
$('#companySearchModal').modal(options);
$('#companySearchModal').modal('show');
...
On that modal dialog I display a list of companies with this PagedListPager on the bottom setup like this:
<div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
<div id="companySearchPager">
#Html.PagedListPager(
Model,
page => Url.Action("CompanySearch",
"Admin",
new
{
sortOrder = ViewBag.CurrentSort,
currentFilter = ViewBag.CurrentFilter,
page = page
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "companySearchModalContent"
}
)
)
</div>
</div>
When I click on a given page element rendered by the PagedListPager control it does call the the Action "CompanySearch" from the Controller "Admin" as specified in the Url.Action but it renders the PartialView that is returned all by itself on the whole page instead of injecting the partial view into the "#companySearchModalContent" Div I've set as the UpdateTargetId in the AjaxOptions of the PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing call.
I figured the PagedListPager would do this. I added some jQuery code to call the appropriate ajax injection "$('#companySearchModalContent').html(data);" but I don't have a way to get the page number, search and sort parameters to come along with that the user clicked on from the pager control and don't know how to set the url and data appropriately in the .ajax code block.
$('#companySearchPager').click(function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
// How to get the page value the user clicked on?
// data: {"page": #},
// How to get the url? This would work if I could get the page #.
// url: '#Url.Action("CompanySearch", "Admin")',
success: function (data) {
debugger;
$('#companySearchModalContent').html(data);
},
error: function () {
showAlert("Employer content load failed.", "warning", 5000);
}
});
return false;
});
I would expect the PageListPager to make that "$('#companySearchModalContent').html(data);" call for me given that I've set the UpdateTargetId in the AjaxOptions of the PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing call.
Thanks for any help...
Fixed the newel post!
Added
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
at the top of the page.

How to pass data from one view to another using RenderAction

I am trying to call a view as modal dialog using RenderAction method. I have to pass some data from the view to the modal dialog's View. How can I achive this?
Below is my code (trimmed as per required) so far.
<table class="table">
<tr>
<th>Project No</th>
<th>Drawing No</th>
<th>Revision</th>
<th>Fabrication</th>
</tr>
#foreach (var irn in Model)
{
<tr>
<td class="projno">#irn.PROJECTNO</td>
<td class="drawingno">#irn.DRAWINGNO</td>
<td class="revno">#irn.REVNO</td>
<td>
<button class="button" type="button" class="btn btn-sm" data-toggle="modal">Add</button>
</td>
</tr>
}
Here is the modal dialog using RenderAction to call another view
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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="myModalLabel">Enter Fabrication Information</h4>
</div>
<div class="modal-body">
<div>
#{Html.RenderAction("Create", "Fabrication");}
</div>
</div>
</div>
</div>
Here are two ways I have tried to invoke the modal dialog
<script type="text/jscript">
$(document).ready(function ()
{
$('button').click(function ()
{
var $row = $(this).closest("tr") // Finds the closest row <tr>
var $projectNo = $row.find(".projno") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
var link = '#Url.Action("Create", "Fabrication")'
// Method 1 -
$('#myModal').modal('show');
//Method 2
$.ajax({
type: "GET",
url: link,
error: function (data)
{ },
success: function (data)
{
$("#myModal.modal-body").html(data);
$('#myModal').modal('show');
},
// in method 2, when I close the dialog, the screen becomes tinted and freezes while it works ok in method 1. why is that?
});
});
});
Here is the Fabrication/Create Conroller method
public ActionResult Create(string projectNo, string drawingNo, string revisionNo)
{
ViewBag.ProjectNo = projectNo;
ViewBag.DrawingNo = drawingNo;
ViewBag.RevisionNo = revisionNo;
return PartialView("Create");
}
When user click Add button, modal dialog should appear carrying ProjectNo information from parent View.
You need to pass the data when invoking controller action.
via JavaScript
When you're sending AJAX request via jQuery, you can use data option property, like in the example below.
If you're sending GET requst, jQuery will automagically append this object to the URL, like so: /Fabrication/Create?projectNo=123&drawingNo=456&revisionNo=789.
Hovewer, if you're sending POST request, URL will not be changed and the data object will be passed inside a request body.
$.ajax({
type: "GET",
url: link,
data: {
projectNo: 123,
drawingNo: 456,
revisionNo: 789
}
error: function (data)
{ },
success: function (data)
{
$("#myModal .modal-body").html(data); // Note that you missed a space between selectors
$('#myModal').modal('show');
},
// in method 2, when I close the dialog, the screen becomes tinted and freezes while it works ok in method 1. why is that?
});
via Razor
You can also use one of the parameter of Html.RenderAction or Url.Action to pass any additional data using anonymous object. This object is always the last function argument, no matter how many arguments you pass before (controller and area names are optional). Note that it's more of a fun fact, because you can't access JavaScript variables directly when using Server-Side methods. It'd be good when rendering default state of your form.
#* Pass custom parameters to controller's action and render it *#
#Html.RenderAction("Create", "Fabrication", new {
projectNo = 123,
drawingNo = 456,
revisionNo = 789
})
#* Create an URL to a controller's action with custom parameters *#
#Url.Action("Create", "Fabrication", new {
projectNo = 123,
drawingNo = 456,
revisionNo = 789
})

Bootstrap modal won't close on click

I am very new to web dev. Still not too familiar with JavaScript. I am making an error message using that will load using code one of our dev guys created for a different page. I created modals that show on a click event and then close on a click event. For this one I am having the modal show based on returned URL parameters. And I am using code I copied from another page one of our dev guys made (not with Bootstrap modals).
The code below makes the modal show, but the buttons used to close the modal don't work. Not sure why.
This is the tag that will append the URL when returned:
(**...?companyName=ACME47 & err1=0 & err2=0 & err3=1**)
When the error values are 1 is loads the page to show the error modal with the text for that error in it.
Here is the code I'm using for the form (not attaching the style sheet, so it looks different).
jQuery(document).ready(function() {
// jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
// Get url parameters
var err1 = new Number($.urlParam('err1'));
if (isNaN(err1)) {
err1 = new Number(0);
}
var err2 = new Number($.urlParam('err2'));
if (isNaN(err2)) {
err2 = new Number(0);
}
var err3 = new Number($.urlParam('err3'));
if (isNaN(err3)) {
err3 = new Number(0);
}
console.log('err1: ' + err1); // Writes a message to the browser console [f12]
console.log('err2: ' + err2); // Writes a message to the browser console [f12]
console.log('err3: ' + err3); // Writes a message to the browser console [f12]
console.log('CompanyName: ' + $.urlParam('companyName')); // Writes a message to the browser console [f12]
// Display error message function
// Read a page's GET URL variables and return them as an associative array.
if (err1 > 0) {
$("#error-box").show();
$("#error-1").show();
};
if (err2 > 0) {
$("#error-box").show();
$("#error-2").show();
};
if (err3 > 0) {
$("#error-box").show();
$("#error-3").show();
};
});
<div class="modal" id="error-box" style="display: none;" tabindex="-1" role="dialog" aria-labelledby="error-boxLabel">
<div class="modal-dialog" role="document" style="height:200px;">
<div class="modal-content" style="height: 100%;">
<div class="modal-header alert-danger">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title text-danger">Form Submission Error</h4>
</div>
<div class="modal-body alert-danger" style="height: 100%;">
<div class="textWrapper">
<ul>
<li id="error-1" style="display: none;">That email address is already in use. (01)</li>
<li id="error-2" style="display: none;">A company with that name already has an account in this system. (02)</li>
<li id="error-3" style="display: none;">An unknown error has occurred. If your E-Mail or Phone Number was correctly filled in, you will be contacted shortly. (03)</li>
</ul>
</div>
</div>
<div class="modal-footer modal-footer-text">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You shouldn't be using jQuery's show() method to show the modal. Doing so doesn't register it with Bootstrap, so there's nothing to close with elements possessing the data-dismiss attribute. Use Bootstrap's method:
$("#error-box").modal('show');
Note that you may also need to use Bootstrap's show.bs.modal callback to show your error containers. It's possible that they won't be available to jQuery until the modal is initiated.
This is what I think you want see fiddle https://jsfiddle.net/sxh0n7d1/53/
Note: I set all the errors to visible in the fiddle, so that there is something to see how it works.
add this to your javascript
$('.close, .btn-danger').click(function() {
$( "#error-box" ).hide();
});

Render partial view with form in Modal on Html.ActionLink click

I have a page with table where each row has a link "Move".
On clicking of the link I am trying to get the controller GET method called which will in turn render the _MoveReportPartial view in a modal.
Once the user makes the selections in the modal the submit button should post to the Post method of the controller.
If I remove the class attribute (move-modal) from Html.ActionLink(...), it in effect disengages the js file and ignores it. Then it works by opening the _MoveReportPartial in a new window and then consequently posting to the correct method if user clicks submit.
I am trying to get it to open in the modal, but the js I have doesn't work and routes to the POST method instead on "Move" click.
EDIT
Why does the .load call the POST method instead of the GET? How can I change the js? (added event.preventDefault();, still the same behavior is observed)
The move link on the originating view looks like this:
<div class="d20 actionLink">
#Html.ActionLink("Move", "MoveReport", "ReportsWeb", new {id = item.ReportDefinitionId, newReport = false}, new {#class = "move-modal"})
</div>
I have a js file:
$(function () {
$('.move-modal').click(function () {
event.preventDefault();
$('<div/>').appendTo('body').dialog({
close: function (event, ui) {
dialog.remove();
},
modal: true
}).load(this.href, {});
});
});
My ReportsWebController looks like this:
[HttpGet]
public ActionResult MoveReport(Guid id, bool newReport)
{
//some code
return PartialView("_MoveReportPartial", model);
}
[HttpPost]
public ActionResult MoveReport(MoveReportModel Model)
{
try
{
//some code
}
catch (Exception exc)
{
InternetReportingTrace.Source.WriteError(exc);
throw;
}
return RedirectToAction("ListReports");
}
and my _MoveReportPartial looks like this:
<div id="dialog-confirm">
<div align="center">
<h2>Please Confirm</h2>
</div>
#using (Html.BeginForm("MoveReport", "ReportsWeb", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div tabindex="-1" role="dialog">
<div class="modal-content">
<p>Report #Model.Report.Name with ID #Model.Report.ReportDefinitionId </p>
<p>Will be moved to:</p>
#for (int i = 0; i < Model.MoveOptions.Count; i++)
{
<div class="radio">
<label><input type="radio" name="optradio">#Model.MoveOptions[i]</label>
</div>
}
<div>
<input type="submit" value="Move Report" />
</div>
</div>
</div>
}
I don't think you're preventing the default behaviour of the ActionLink properly.
Try:
$('.move-modal').click(function (event) {
event.preventDefault();
$('<div/>').appendTo('body').dialog({
close: function (event, ui) {
dialog.remove();
},
modal: true
}).load(this.href, {});
});
Because it's a jQuery handler, you can use event.preventDefault() instead of return false;. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior before that point. Using event.preventDefault() as the first line in the handler means you can guarantee that the default navigation behavior will not fire.
Secondly, your .load method call is wrong.
Change
.load(this.href, {});
to
.load(this.href);
The documentation at api.jquery.com/load states "The POST method is used if data is provided as an object; otherwise, GET is assumed." Because you're sending it an empty object, it assumes you want to use POST. There's no need to do this.

Twitter Bootstrap alert message closes without pressing close button

I have a problem with alert messages. I want to use the alert message as a warning to the user after a particular action has been performed. The issue I am facing is that the message shows and then closes on its own without user closing the message.
<div class="row-fluid">
<div class="alert span10 offset1" style="display: none" id="changeStatusMsg">
<a class="close" onclick="$('.alert').hide()" href="#">×</a>
<strong>Status has been changed.</strong>
</div>
I am using jquery to show the message -- $('#changeStatusMsg').show();
I used the solution mentioned here
But it does not help in my case.
function changeStatus(status, widgetExternalId){
$.ajax({
url : 'Controller',
data : { 'widget' : widgetExternalId,
'method' : (status == 'I' ? "activate" : "inactivate")
},
success : function(data) {
window.location = "myaccount.jsp";
$('#changeStatusMsg').show();
}
}
});
}
It is probably do to the fact you are not calling the action that is opening it. So the page is refreshing.
If you are doing it inline:
onclick="$('#changeStatusMsg').show();return false;"
If with a click event
$(".foobar").on("click",function (event) {
event.preventDefault();
$("#changeStatusMsg').show();
});

Categories