How to refresh content of iframe from controller in ASP.NET MVC? - javascript

I have a question about combination of asp.net mvc and iframe.
I'm trying to edit retrieved data from db on iframe.
The problem is that when the page firstly loads the parent contents, iframe contents is also loaded and can't be edited later.
public ActionResult StudentDetail(string id)
{
Student student_data = null;
if (id != null)
{
student_data = getId(id);
}
else
{
return null;
}
return PartialView("StudentDetail",student_data);
}
As you can see above code,if any ID is selected by hyperlink of view,
it returns partial view for iframe.When it comes to this page at the first time,
becuase any Id isn't selected,it returns null.
Below code is snippet of the parent view.This calls controller and content is set by null when it comes to loading this page at the first time.
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-content">
<div class="modal-body">
<div class="embed-responsive embed-responsive-16by9">
<iframe id="myFlame" class="embed-responsive-item" src="/Home/StudentDetail" frameborder="0" allowtransparency="false" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
After loading the parent page and iframe page, user push the hyperlink to pop up the iframe to edit data.The snippet of code is below,it calls javascript to send id to controller
<td>#student.id</td>
Code of javascript is below.
<script>
var TeamDetailPostBackURL = '/Home/StudentDetail';
$(function () {
$(".anchorDetail").click(function () {
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myFlame').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
//$("#closebtn").on('click',function(){
// $('#myModal').modal('hide');
$("#closbtn").click(function () {
debugger;
$('#myModal').modal('hide');
});
});
</script>
After pushing a hyperlink,javascript send the data to controller and retrieve data from db and return partialView of StudentDetail.cshtml.but it still shows empty iframe.
How can I refresh the content of iframe?

Related

Dynamically generated content for html page after button click

I have html page where I want to open dialog by button click and content of dialog should be dynamically generated.
The idea is the following:
I click button
JS(ajax)run my flask route , where http request to other site is executed and then json is returned
The returned json is passed to js (or html), then this json is parsed and according to found information, the elements (images as an example) are displayed in opened dialog
Python:
#app.route('/sales_inventory', methods=['POST'])
def tm_inventory(user):
response = some_function("authKey")
return make_response(jsonify(response)))
HTML:
<button class="inventory">Inventory</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
</div>
</div>
Elements should be generated inside div .modal-content
JS:
$(."inventory").click(function () {
$.ajax({data: {
user: $(this).next().text()
},
type: 'POST',
url: '/sales_inventory'
})
Js is not completed, because I have no idea how should it be
The class name and . should be wrapped by a string quotation. In your code the class indicator . is outside the string quotation.
According to your question your server is responding JSON data, so you should add dataType as JSON of your AJAX. Also add a success callback function which is automatically called when the server response. Of success function there is a parameter data which contains the response data as an object (JSON) and now using this data you can prepare your HTML and set in the certain place of the modal.
JS:
$(".inventory").click(function () {
// ^^^^^^^^^^^^
$.ajax({
data: {
user: $(this).next().text()
},
dataType: 'JSON',
type: 'POST',
url: '/sales_inventory',
success: function(data) {
// var prepared_html = using `data`
// $('.modal-body').html(prepared_html);
}
})
})
HTML:
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
</div>
</div>

Check data in Succes ajax function to reidrect to specific view

I am calling a javascript function on click which calls an action method that returns either a partial view or full view. I want to load partial view in a modal popup and if it is a full view, then just want to redirect it.
View
foreach(var productTemplate in Products)
{
Add New Product
}
<div class="modal fade" id="mymodel" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Shared Products</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="mymodelbody">
</div>
</div>
</div>
<script>
var loadModal = function (productId, customerId) {
$.ajax({
type: 'GET',
url: '/NewProductTemplate/CreateNewProduct',
cache: false,
data: {
productId: productId,
customerId: customerId
},
dataType: 'html',
success: function (data) {;
$("#mymodelbody").html(data);
$("#mymodel").modal("show");
}
});
}
</script>
NewProductTemplateController code:
public ActionResult CreateNewProduct(Guid productId, Guid customerId)
{
var sharedProduct = _productTemplateService.GetSharedProducts(productId);
var _finalSharedProducts = (sharedProduct.Any(t => t.productId != productId));
if (_finalSharedProducts)
{
var sharedProdctTemplate = _productTemplateService.GetSharedProduct(productId);
return PartialView("_shared", new SharedModel
{
SharedProduct = sharedProdctTemplate
});
}
else
{
_productTemplateService.CreateNewProduct(productId);
return RedirectToAction("Details", "ProductTemplate");
}
}
Problem is that when controller returns a full view, it loads in a modal popup which I don't want. I just want to check the data in success function and decide whether to load modal for partial view OR redirect to a full view. I am not sure how to do it.
Can please someone help me here? Thank you!
UPDATE:
I was able to make it work like
if (data.indexOf('<!DOCTYPE html>') != 0) {
$("#mymodelbody").html(data);
$("#mymodel").modal("show");
} else {
window.location.href = '/ProductTemplate/Details?productTemplateId=' + productId;
}
One more question:
Is there any way that I can create a ProductModal object in javascript and pass it to the Details action method of ProductTemplate?
If your action returns your whole page, it will include the <!DOCTYPE html> and <html> tags. You can check if the result starts with '<!DOCTYPE html>' for example to make to check if it is the whole page or not.
success: function (data) {
if (!data.startsWith('<!DOCTYPE html>')) {
$("#mymodelbody").html(data);
$("#mymodel").modal("show");
} else {
window.location.href = '<redirect url here>';
}
}

Modal Popup not loading in partial view when calling from parent view

I am trying to call a modal on a partial view from a view but am not getting ajax success call, but dont know how to do it:
Here is what i have, javascript ajax code on my page:
var TeamDetailPostBackURL = '/BMApproval/GetMeetingApprovalData';
$(function () {
$(document).on('click','.LeadCode', function () {
//$(".LeadCode").click(function () {
debugger;
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
alert("load");
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "dataValue": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
And parameters I am passing in ajax call
<td>#LPOPoint.LeadCode</td>
Also calling modal popup in the same javascript page which will popup on the partial view.
<div id='myModal' class='modal' style="overflow-y:hidden;">
<div class="modal-dialog" style="overflow-y: scroll; max-height:85%; margin-top: 20px; margin-bottom:20px;">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div></div>
I searched a lot in various forums but couldn't get any solution.
When am clicking on html link the popup doesn't load in the partial view.
And ("Dynamic content load failed."); is displayed as it doesn't get to success.
Basically I want to view data in modal popup in partial view based on the parameters from parent view. Any help would be appreciated.
At the first sight looks like you need TeamDetailPostBackURL variable to contain a proper URL including scheme, host (and port if needed) like 'http://example.com/BMApproval/GetMeetingApprovalData'
You can specify error parameter in the error callback to see what exactly is wrong
error: function (error) {
console.error(error)
alert("Dynamic content load failed.");
}

Insert multiple label fields using for loop in a form

I'm using jquery ajax in codeigniter framework to load a pop up modal on button click. I pass ajax request to a function in controller and receive some data which should be shown in my pop up modal. Number of labels of the modal is depend on the size of the array received by the ajax request.
I have no idea how to do this. But I tried of passing the size of the received array to a hidden type input field in form created on the pop up modal.
Following is my javascript.
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','#btn_more', function() {
empId = $('#employeeId').html();
fiter_employees(empId);
});
function fiter_employees(empId){
var empSet ={
empId: empId,
method: 'ajax'
};
var empSentUrl = 'http://localhost/eventmanagementsystem/index.php/employee/get_emp_positions';
$.ajax({
type: 'POST',
dataType: 'json',
url: empSentUrl,
data: empSet,
success: function(data){
$('#modal_pkg1').html(data.empPosition.length)
$('#employeePositions').modal();
}
});
}
});
In my pop up model I used the following codes which is not succeeded.
<div id="employeePositions" class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Employee Name :</h4><br/>
<form>
<?php
for ($i=0; $i < ?>
<input type="hidden" id="modal_pkg1" value="modal_pkg1" />
<?php
; $i++) { ?>
<h4 class="modal-title" id="event_name"></h4>
<?php
} ?>
</form>
Can someone tell me the correct me of doing this please...
Your PHP code has executed the moment you load the page, so when you change the modal_pkg1 value, nothing will happen.
Also, the foor loop itself will not work on load, as it's expecting a number that is not there.
I suggest you do it fully in JS, remove all php code from your script; something like below :
in your Ajax success function :
.success(function(data){
var htmlStr = ''
for(var i=0;i<data.empPosition.length;i++){
htmlStr+='<whatever html element you want to display>'
}
$('form').html(htmlStr) // add the generated html string to the <form> element
$('#employeePositions').modal();
}

How to show Ajax response as modal popup

I have a link on clicking it is sending ajax request and getting response successfully which is html file and I am appending to a div, but I need to show that div as modal popup and I tried something below.
in html file
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
<div id="login_for_review" data-toggle="modal" data-target="#reviewLoginModal"></div>
in js file
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');// I tried to show this response as modal popup
},
error: function(output){
alert("fail");
}
});
});
output file
<div class="centerForm modal fade" role="dialog" style="margin-left: 35%;" id="reviewLoginModal">
<div class="modal-dialog modal-sm" >
<div class="modal-content">
// here I have login form
</div>
</div>
but I am not getting this html output as modal pup instead I am getting black screen can anyone help me how to do this?
In Bootsrap modal popup, You can use plain way to show modal which don't need pre-defined modal div container . see at modal
For E.g
$.ajax({
url: "url",
type: 'POST',
dataType: "html",
data:{id:params},
success: function(data, status, xhr) {
if(data==""){
window.location.href="/";
}
else{
BootstrapDialog.show({
title: "Modal Tital",
message: function(dialogRef){
$mydata = $($.parseHTML(data));
return $mydata;
},
onshow: function(dialog){
// and css change if need, eg.
dialog.$modalHeader.css("float","none");
},
onshown:function(dialog)
{
// event after shown
},
onhide:function(dailog)
{
// event on hide
}
});
}
},
statusCode: {
401: function () {
alert("Your session has been expired");
}
}
});
I solved this problem by creating modal and by removing data-toggle and data-target and just appending response to that modal div
Code For modal div
<div id="login_for_review" class="modal hide" role="dialog">
</div>
Code For hyperlink
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
Code For ajax call
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');//now its working
},
error: function(output){
alert("fail");
}
});
});

Categories

Resources