Partial view in a dialog - asp.net-mvc

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!

Related

How to access bootstrap from any view in MVC

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");
}

jQuery UI Modal Dialogs in MVC

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.

How to refresh the contents of the MVC 3 partial View placed in JQuery Dialog

My situation is very common.
I have a master detail environment on my web administration.
I need to be able to select one record among around 3500 from a dialog.
This is the reason why I need pagination.
My implementation is using JQuery Dialog and MVC 3 partial View in it.
I need the possibility to refresh the contents of the already opened JQuery dialog without refreshing the underline page.
After any page click on the partial View in the JQuery dialog
<dt>
B
</dt>
<dt>
C
</dt>
My page has been refreshed and the the JQuery dialog disapeared.
Is there some kind of solution for this situation ?
It's not very clear if the News/SelectArtist is the controller action that should return your partial view, but here how I would do this.
You can call this action via ajax and refresh the content of your jQuery dialog.
Suppose your jQuery dialog has a div wrapping the entire content (from your partial view):
<div id="dialog-content">
...
<!-- this is the content of your partial view -->
</div>
Add a css class to each of your page links and a data-pageid to call your SelectArtist action like this:
<dt>
<a class="page-trigger" href="#" data-pageid="2">B</a>
</dt>
From a script block:
$(function() {
$('.page-trigger').click(function() {
var pageId = $(this).data('pageid');
$.ajax('/News/SelectArtist?PageId=' + pageId, { }, function(data) {
$('#dialog-content').html(data);
});
});
});
Make sure your SelectArtist action have the [HttpPost] attribute. Your dialog content would update without a page request.
[HttpPost]
public ActionResult SelectArtist()
{
int pageId = int.Parse(Request.QueryString["pageId']);
...
return PartialView(viewModel);
}

ASP.NET MVC multiple forms, staying on same page

I have forms located in multiple areas in my layout page (not nested).
I have a partial view which performs a post to controller action.
What action result do I return in that post to keep the user on the current page?
Is jquery/ajax my only option? I would rather a solution that didn't depend on javascript, maybe even a solution that degrades nicely.
You can use the Request.Referrer property to see what page the user has come from and then just use that to redirect them back there.
This does introduce other issues, e.g. losing ModelState, so you'll have to design for that. Also note that some users can block sending referrer information in their requests to the server - so the Referrer property can be null.
I would recommend using AJAX and then falling back on this.
You just need to do a RedirectToAction("") back to your main view.
To post a form without submitting the whole page, which refreshes the browser, you need to use Ajax/jQuery. The degraded solution is to submit the whole page like you would with a normal form.
Here's how I do it with jQuery.
Html:
<div id="RequestButtonDiv">
<button id="RequestButton" name="Request" type="button">Request</button>
</div>
This calls AddToCart on my Request controller when the RequestButton button is clicked. The response is placed inside the RequestButtonDiv element.
<script type="text/javascript">
$(document).ready(function () {
$('#RequestButton').click(function (event) {
$('#RequestButton').text('Processing...');
$('#RequestButton').attr('disabled', true);
submitRequest();
});
});
function submitRequest() {
$.ajax({
url: '<%: Url.Action("AddToCart", "Request", new { id = Model.RowId, randomId = new Random().Next(1, 999999) } ) %>',
success: function (response) {
// update status element
$('#RequestButtonDiv').html(response);
}
});
}
</script>
Controller action:
public ActionResult AddToCart(int id)
{
var user = AccountController.GetUserFromSession();
user.RequestCart.AddAsset(id);
return View("~/Views/Assets/Details_AddToCart.ascx");
}
The controller returns a partial view. You could also return Content("some stuff") instead.
Holler if you have questions or need more detail.

MVC-pop up windows

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

Resources