How does one go about displaying a controller action inside of jquery modal dialog?
Firstly you'll need your Javascript to load a url via ajax, this will depend on which kind of modal you are using etc, there's a ton of libraries out there. I will assume you are using the basic JQuery UI dialog Modal.
Example Link
<!-- this points to your action below.. -->
<a class="some-link" title="title here" href="mycontroller/test">testing</a>
Example Javascript (quick example found on google, many examples out there..)
$(document).ready(function() {
$('.some-link').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
autoOpen: false,
title: $link.attr('title'),
});
});
});
Now you need to make sure your action doesn't render the main layout when providing the content for the modal via the ajax request.
Here's a really simple method of doing that by replacing the base layout with an empty view for ajax requests. This isn't the best method but it's the simplest for this case ;)
Example Action
public function testAction()
{
if($this->getRequest()->isXmlHttpRequest()) {
$this->layout('application/layout/ajax-layout');
}
return new ViewModel(array()); // ..
}
application/layout/ajax-layout.phtml
<?php echo $this->content ?>
I think you want this kind of code http://jqueryui.com/dialog/#modal-message
inside the just display your action
Otherwise it's about to open an url into your modal it's like that http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/
Related
I want to show a popup using bootstrap which is defined in another view(e.g. SaveRecord.chhtml).
Is there any way to access bootstrap dialog box from any View(e.g. Registration.cshtml)
like give below
$(document).ready(function () {
$('/BootStrap/SaveRecord/.mymodal').modal('show');
}
where "mymodal" is bootstrap-id of given below
You really can't access elements like this as jQuery on it's own would require those elements to be present in the DOM in order to access them.
Create A Partial View And Load It As Needed
You could consider creating a Partial View that contained all of the necessary markup for your specific Modal and then when you needed to access it, simply load it into the DOM (if it doesn't already exist) via an AJAX call and then display it :
$(function(){
// Load your Partial View (assumes a Controller Action will route to it)
$.get('#Url.Action("GetYourPartialView","YourController")', function(html){
// Insert this element into the DOM
$('body').append(html);
// At this point it should exist, so load it
$('.myModal').modal('show');
});
});
This would assume that a Controller Action existed that would point to your specific Partial View that contained your modal (and only your modal) :
public ActionResult GetYourPartialView()
{
return View("YourPartialViewName");
}
Consider Using the Layout
Another solution that you could consider using would be to define your various modal "templates" that you might use throughout your solution at the Layout-level so that any pages that would rely on those would be able to access them.
You can use Partial Views.
Create your partial view _MyModal.cshtml under Views/Shared folder
In every view where you want to use it:
#Html.Partial("~/Views/Shared/_MyModal.cshtml")
On your javascript file: $('#mymodal').modal('show');
Here are the steps:
1.Make your bootstrap popup view a partial view
2.In your regular view, add a div which will have the modal content
<div id="divModalContent">
</div>
3. In your regular view, Add html button with onclick function
<input type="button" class="btn btn-default" value="{Your Text}" onclick="LoadSaveRecordModal()" />
4.Your JS:
function LoadSaveRecordModal()
{
$.ajax(
{
type: 'POST',
url: '{your url}',
data: data, //if required
success: function (result) {
$("#divModalContent").html(result); //load your modal content inside the div
$("#mymodal").modal('show'); //show the popup
},
failure: function (ex) {}
}
);
}
4.Your action method
public ActionResult GetSaveRecordModal(//get data if its post request)
{
//code
return PartialView("SaveRecord");
}
I have managed to get the JQuery Modal dialog to show and within it, I load a partial view:
var url = '#Url.Action("ShowCarDetail", "Car")?id=' + id;
$('#dialog-modal').dialog(
{
title: "Car Detail",
width: 600,
height: 500,
draggable: false,
close: function (event, ui) {
$(this).dialog('close');
}
});
$('#dialog-modal').load(url, function()
{
$(this).dialog('open');
});
So that works fine. The problem is that when the dialog is closed, and I re-open it, the data is not refreshed. I have a DateTime on that partial view that tells me this so leaving it for a few seconds still shows me the old values.
how can I force the modal dialog to load correctly (without it using the old html that may have been rendered from the previous request)?
also - if the partial view has some actions like a submit or something, will the dialog still remain open or will this refresh the page fully? I want to be able to have that modal dialog similar to an iframe style where any actions that happen within the page in the modal will still be there and be updated without the page having a full refresh and the dialog closing.
thanks
Regarding your question:
also - if the partial view has some actions like a submit or
something, will the dialog still remain open or will this refresh the
page fully? I want to be able to have that modal dialog similar to an
iframe style where any actions that happen within the page in the
modal will still be there and be updated without the page having a
full refresh and the dialog closing.
The page will be refreshed fully with a normal form. To achieve what you describe, use an ajax form which does a post to a controller method and returns a partial view. Then have a success callback for the ajax form, which would replace the contents of a div (within the open dialog) with the response content (which would be the partial view returned from the post).
Simplified example...
View:
<div id="dialog-modal">
<p>Some optional static content here (within the dialog)
that should not change when the form is submitted.</p>
<div id="dialog-content">
#using (Html.BeginForm("MyAction", "MyController", null, FormMethod.Post, new { #id="MyForm" }))
{
#Html.EditorFor(x => x.Foo)
<input type="submit" value="OK" />
}
</div>
</div>
Controller:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
// Do some stuff here with the model if you want
MyNewModel newModel = new MyNewModel();
return PartialView("_MyPartialView", newModel);
}
JavaScript:
$(function () {
$('#MyForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (xhr) {
$('#dialog-content').html(xhr);
}
});
return false;
});
});
Note that this implementation will replace the form, so you could put the form outside the div that gets replaced if needed, or have a different form in the partial view that gets returned if you want different forms submitted within the dialog in series. It's flexible to tweak to your needs. It also will not close the dialog until you explicitly call close on it, or affect any content outside of the replaced div's content. Hope this helps!
Excuse me for the simplistic question, but I've had a hard time getting my head around this. I have a View (.cshtml) with the following contents (Per this sample):
<div id='dlgLogin'>
<h1>Log in</h1>
<table>
<tr>
<td>Username:</td>
<td>#Html.TextBox("username")</td>
</tr>
<tr>
<td>Password:</td>
<td>#Html.Password("password")</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(function () {
$("#dlgLogin").dialog({
modal: true,
autoOpen: true,
resizable: false,
buttons: {
Login: function () {
// perform login
$.post("#Url.Action("Login", "Home")",
{
username: $('#username').val(),
password: $('#password').val()
},
function( data, status, xhr ) {
if(data.Success){
alert('great'); // do something
$('#dlgLogin').dialog("close");
$('#divLoginButton').load("#Url.Action("GetLoginButton", "Home")");
} else {
// do something else
}
});
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
</script>
Basically the View will always load in a jQuery UI Dialog whenever it's opened, that is, it's the responsibility of the View itself to place it's own content inside a jQuery UI dialog. I've done this so that I can override the OnAuthorzation() event of my Log In and redirect the user to a pop up when they are required to log in. I have 3 questions:
1. How would I display a loading animation (a .gif) when the form is posted back to the server? With this approach? I'm aware that if I used an Ajax.BeginForm I could have specified a UpdateTargetId which would have been used as an area to load the animation during post back, but how would I achieve that effect with this approach?
2. How would I attach and handle the success event to the form post above? i.e. When the form is posted back to the Login Action of the Home Controller.
3. I've seeing at least 3 or 4 different approaches to displaying dialogs in MVC. What is the correct way to do this? Is the approach that I posted above considered good/mvc-friendly practise, if not what do you recommend?
1 How would I display a loading animation (a .gif) when the form is posted back to the server?
Take a look at ajaxSend:
<div id="loader"></div>
$("#loader").bind("ajaxSend", function () {
$(this).show();
}).bind("ajaxStop", function () {
$(this).hide();
}).bind("ajaxError", function () {
$(this).hide();
});
2 How would I attach and handle the success event to the form post above?
I don't understand what you are asking. You have attached an anonymous function to handle the post to the server in your sample code.
3 I've seeing at least 3 or 4 different approaches to displaying dialogs in MVC. What is the correct way to do this?
There is no best way of showing a dialog.
You can use the approach you showed with loading the dialog content with the page, but i would add a style="display: none;" to the dialogs div. Another approach would be to load the dialog content with ajax from a partial view when opening the dialog.
I need to create pop up windows in mvc(not new tab in browser). Does anyone know how to do this?
One possibility is to use jquery ui dialog.
EDIT
The idea would be to have an ajax action that returns a partial view. The result of that action (html) is placed inside the container of the popup and on the success handler of the ajax call you open the popup. Here is some sample code:
#Ajax.ActionLink("Open popup", "SomeAction", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, OnSuccess="openPopup" })<br />
<div id="result" style="display:none;"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#result").dialog({
autoOpen: false,
title: 'Title',
width: 500,
height: 'auto',
modal: true
});
});
function openPopup() {
$("#result").dialog("open");
}
</script>
Then you have to add the action in the controller that returns the partial view
[HttpGet]
public PartialViewResult SomeAction()
{
return PartialView();
}
Place whatever you need in the partial view, you may also include parameters in the action, etc.
Good luck!
Most obvious way is using one of js frameworks. Personally I prefere jQuery UI dialog control.
Please check http://jqueryui.com/demos/dialog/ for detailed information about it.
Also you may check ASP.NET MVC modal dialog/popup best practice (it's question similar to yours)
Of course if you need some simple popup you always may use alert('Im popup');
Update according your latest request
To open some url in new window you may use next javascript:
function OpenDialog() {
window.open("some url", "DialogName", "height=200,width=200,modal=yes,alwaysRaised=yes");
}
But result really depends on browser. Most of them open this modal window not in new tab but in new browser instance.
This topic might help you aswell:
JavaScript open in a new window, not tab
I am looking to standardize the processing of ajax #anchors at the server side, using MVC.
Before a controller action is invoked I want to convert every request with ajax anchors into a request without ajax anchors, so that the controller code does not know there were anchors in the request:
For example:
1) /user/profile#user/photos should be treated as /user/photos
2) /main/index#user/profile/33 should be treated as /user/profile/33
What is the best technique in MVC to accomplish that?
This should necessarily be done on the client side, probably using jquery as everything that follows the # sign is never sent to the server.
I too struggle with same issue and I solved this problem after looking at Visual Studio 11 Developer Preview template code. I added following code in my _layout.cshtml, please note we must load jquery.mobile*.js file after following script tag:
<script type="text/javascript">
$(document).bind("mobileinit", function () {
// As of Beta 2, jQuery Mobile's Ajax navigation does not work in all cases (e.g.,
// when navigating from a mobile to a non-mobile page, or when clicking "back"
// after a form post), hence disabling it. http://jquerymobile.com/demos/1.0a3/#docs/api/globalconfig.html
#{
if (ViewBag.JqueryMobileAjaxEnabled != null && ViewBag.JqueryMobileAjaxEnabled == true)
{
#: $.mobile.ajaxEnabled = true;
}
else
{
#: $.mobile.ajaxEnabled = false;
}
}
});
</script>
**<script src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script>**