How to access bootstrap from any view in MVC - asp.net-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");
}

Related

Get ID from modal window

I have a block of code running 3 times that will display some books and have a button to add a review.
Review button fires a modal popup with form to fill to create a review.
I am feeling dumb but I cant find a way to get a ID of a bookto use to create a review.
Was thinkink to display it within add reiew button params but dont know how to pass it after form submit (with other button pressed withtin form itself)
Template view for each book
<div class="book-#{book.id}">
... other stuff
<button class="review-create"> Write Review </button>
</div>
Javascript to display modal
$('.review-create').click(function(e) {
e.preventDefault();
// might not be parent() here but you can call parent() as many times as you want
var bookId = $(e.currentTarget).parent().attr('class').split('-')[1];
// other stuff for ajax or pass bookId into modal method
// Modal.displayForBook(bookId);
});
Now that your modal has the bookId, you can submit it through ajax by just referencing the variable. Hope this helps.
EDIT:
Because you can't edit the current script, you can write a new script in the view.
_book.html.erb
<script type='javascript/text'>
$('modal-button').click(function(e) {
$('review-create').attr('id', "#{book.id}");
});
</script
modal.html.erb
Your modal will submit ajax, dont make it do the form_for helpers
<script type='javascript/text'>
$('form.create').on('submit', function(e) {
var bookId = $(e.currentTarget).parent().attr('id');
// ajax call here
// on success, $(e.currentTarget).parent().attr('id', null)
});
</script>

Partial view in a dialog

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!

Zend Framework 2 & jquery modal dialog

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/

Difference in RedirectToAction and ActionLink causing .post() not to work

I have application that redirect user to Index page of some controller from account controller using RedrirectToAction(), after login.
RedirectToAction("Index", "MyController");
It redirects me to //MyApp/MyController/
I also have navigation on MasterPage view, I use ActionLink:
#Html.ActionLink("Index", "SomeOtherController")
... (other links)
That redirects me to //MyApp/SomeOtherController
Problem is in **/** character on the end of the first route. I have partialView on master page that onClick calls jQuery .post().
function SomeFunction(id) {
$.post("Controller/Action", { id: id },
function () {
... some code
});
}
But when I call that function after redirect from login it trys to access this route:
/MyController/Controller/Action
that doesn't extist. If I change my post call to
$.post("../Controller/Action", ...
it works fine, but then doesn't work for nav links becouse they don't have **/** on the end of route.
What should I do? How to get unique paths from RedirectToAction and ActionLink, with or without **/** on the end?
NOTE:
I can use <a></a> for navigation on master page and enter path with **/** on the end, but I would rather use ActionLink
The key here is that you need MVC to generate your routed URLs for you to pass into your jQuery functions.
1.If your jQuery code is nested within your View, the you can do the following:
function SomeFunction(id) {
$.post('#Url.RouteUrl("Action", "Controller")', { id: id },
function () {
... some code
});
}
2.If your jQuery code is located in an external file (such as myScripts.js), then you will need to somehow pass the MVC generated route to your jQuery function. Since this is not tied to an element directly, you probably would be best served to set this as a hidden element in your view.
View
<input type="hidden" id="jsRoute" value="#Url.RouteUrl("Action", "Controller")"/>
JS
function SomeFunction(id) {
$.post('$("#jsRoute").val()', { id: id },
function () {
... some code
});
}

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.

Resources