display json in popup returning ActionResult - javascript

I have a custom controller in mvc and the ActionResult is:
[HttpPost]
public ActionResult Details([DataSourceRequest]DataSourceRequest command, int id)
{
//var userDetail = _CustomerDetail.GetAllCustomers();
var genericDetail = _GenericDetail.Table.Where(x => x.EntityId == id).Select(z => new { z.Key, z.Value }).ToList().AsQueryable();
//var userData = from ud in userDetail
// join gd in genericDetail
// on ud.Id equals gd.EntityId
// select new { gd.Key, gd.Value };
DataSourceResult result = genericDetail.ToDataSourceResult(command);
return Json(result, JsonRequestBehavior.AllowGet);
}
which is returned an object like this:
{"Data":[{"Key":"Gender","Value":"F"},{"Key":"FirstName","Value":"h"},{"Key":"LastName","Value":"h"},{"Key":"DateOfBirth","Value":"1914-05-03"}],"Total":4,"AggregateResults":null,"Errors":null}
and my ajax and bootstrap popup codes are:
$.ajax({
type: "POST",
url: "/UserDetails/Details",
data: { id: dataItem.Id },
success: function (result) {
$('#dvDetail').html(result);
$('#myModal').modal('show');
},
error:function(){
alert('fail');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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">User Detail</h4>
</div>
<div class="modal-body">
<div id="dvDetail"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I want to display my json object returning in 2 columns which are Key and Value and try many solutions of stackoverflow but did not success.
can anybody help me?

You need to give that object a template to render the data as a two column table/div, etc.
You can define a template function like this:
userDetailTemplate = function(data){
var renderRow = function(val){
return "<tr>" + val + "</tr>";
}
var renderCol = function(val){
return "<td>" + val + "</td>";
}
var renderContent = function(val){
return "<table>" + content + "</table>";
}
var content = [];
for(i=0; i<data.length; i++){
var key = renderCol(data[i].Key);
var val = renderCol(data[i].Value);
content.push(renderRow(key+val));
}
return renderContent(content.join(''));
}
In the Ajax callback, you need to call this template function.
success: function (result) {
$('#dvDetail').html(userDetailTemplate(result.Data)); // or this should be result. You need to try either of these.
$('#myModal').modal('show');
},

Related

How to get a value from controller and use this in javascript using MVC?

In my project , I get the error and success notifications as TempData from controller and in view , if they're not null I show user a notification seperately. Ever since I start to use FilePond , my TempData values became invisible. Hence, I try to add if-else conditions to javascript so I can show the notifications again. But the problem is , I can't get the TempData value to use in javascript. I researched and tried all recommendations but it still returns null. Any Idea how can I fix this ? I'm so close to end this but the only problem is TempData now.
My Controller (I made it shorter but in debug , I can get the tempdata value so nothing is wrong in here)
[HttpPost]
public async Task<IActionResult> Create(SaveCommand command)
{
TempData["error"] = _localizationService.GetLocalizedHtmlString("error");
return View();
}
View / Javascript Part (var test returns null)
<script type="text/javascript">
var myJsVariable = null;
var test = #Json.Serialize(#TempData["error"]);
$(document).ready(function (e) {
pond = FilePond.create(
document.querySelector('#ImageUrl'), {
allowMultiple: true,
instantUpload: false,
allowProcess: true
});
var frm = $('#form2');
if (myJsVariable != null) {
frm.submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
formdata.append('ImageUrl', pondFiles[i].file);
}
pond.removeFiles(pondFiles);
$.ajax({
url: "/test/create/",
data: formdata,
processData: false,
contentType: false,
method: "post"
}).done(function (response) {
});
$("#modal3").modal('show');
})
}
else if(myJsVariable ==null){
console.log("fail")
frm.submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
formdata.append('ImageUrl', pondFiles[i].file);
}
pond.removeFiles(pondFiles);
$.ajax({
url: "/test/create/",
data: formdata,
processData: false,
contentType: false,
method: "post"
}).done(function (response) {
});
$("#modal2").modal('show');
})
}
});
</script>
}
ps : This was a problem for a while so I created a random myJsVariable to understand where the problem is. But instead of using this , I need to use my tempdata values. (I cant even show my tempdata values inside my modals.)
This was a problem for a while so I created a random myJsVariable to
understand where the problem is. But instead of using this , I need to
use my tempdata values. (I cant even show my tempdata values inside my
modals.)
Well, the way are you trying to Retrieve value from temp data is incorrect. Here '' is very important. You could use below pattern to extract your #TempData["error"] then bind to javascript easily.
var tempData = ('#TempData["error"]');
Working Example For You:
Controller:
public IActionResult TempDataView()
{
TempData["error"] = "Temp Data From Controller";
return View();
}
Modal:
<div class="modal" tabindex="-1" role="dialog" id="formModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header" id="formModal">
<h5 class="modal-title"></h5>
</div>
<div class="modal-body"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<a onclick="BindTempDataToJavascript('#Url.Action("TempDataView","Todo",null,Context.Request.Scheme)','Bind Temp Data To Javascript')" class="btn btn-success text-white"><i class="fas fa-random"></i> Bind Temp Data To Javascript</a>
Script:
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script>
<script type="text/javascript">
BindTempDataToJavascript = (url, title) => {
//Retriving Temp Data and Binding to Javascript variable
var tempData = ('#TempData["error"]');
alert(tempData);
console.log(tempData);
$("#formModal").find(".modal-body").html(tempData);
$("#formModal").find(".modal-title").html(tempData);
$("#formModal").modal('show');
};
</script>
Output:

Display external link in modal panel

I have searched for this issue and although some of the solutions work none of them fit my issue.
I am creating links dynamically using ajax calls. When any of the links (styled as button) is clicked I need to show http:\\<IP-address> in the modal.
When links are created and I use "inspect" and copy what is rendered and paste it on top of the page and click it, it does show the content in modal pop up, so I know the script that displays content in modal works. But when I click on actual, dynamically created, links it opens the pop up with no content.
Here is a watered down version of what I have and what I have tried:
Modal popup:
<div class="modal fade" id="printerInfoModal" role="dialog" aria-labelledby="mainModalLabel" aria-hidden="true">
<div class="modal-dialog fade in">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<asp:Label ID="lblModalTitle" runat="server" ClientIDMode="Static" Text=""></asp:Label></h4>
</div>
<div class="modal-body">
<iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>
</div>
<div class="modal-footer">
<button id="btnCloseModal" class="btn btn-info" data-dismiss="modal" aria-hidden="true" aria-label="Close">Close</button>
</div>
</div>
</div>
</div>
// Get a list of printers and for each get its status, printer property includes IP address
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Services/ps.asmx/GetPrinterMapping",
cache: false,
data: "",
success: function (response) {
if (response !== "") {
try {
jResponse = JSON.parse(response.d);
$.each(jResponse, function (index, value) {
var printer = value;
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Services/ps.asmx/GetPrinterStatus",
cache: false,
data: JSON.stringify({ PrinterHostnameIPAddress: printer.IPAddress }),
success: function (result) {
if (result !== "") {
var printerIP = 'http://' + printer.IPAddress;
//var redir = 'openInfo("' + printerIP + '")';
if (status == "Ready") {
$('<div/>', { class: 'col-sm-2' })
.append($('<a/>', { id: 'printer' + printer.IDN, class: 'form-control btn btn-success btn-block extLink', style: 'margin-bottom:5px', href:printerIP, text: status.replace(/\"/g, '') }))
.appendTo($('#printerStatusTable'));
// Not sure if below two lines work!
//It seems I cnnot add data-target: 'xxx' in attributes list part of "append"
$('#printer' + printer.IDN).attr('data-target', '#printerInfoModal');
$('#printer' + printer.IDN).attr('data-toggle', 'modal');
},
error: function (result) {
},
failure: function (result) {
}
});
})
$('#printerStatusTable').find('a').attr('data-target', '#printerInfoModal');
$('#printerStatusTable').find('a').attr('data-toggle', 'modal');
// Another think I tried
$('#printerStatusTable').find('a').attr('onclick', 'blah(' + $(this).attr('href') + ');');
JS:
// this function is hit if I copy/paste the html of the the link/button and click it; otherwise it is not called
$('.extLink').click(function (e) {debugger
e.preventDefault();
var frametarget = $(this).attr('href');
//clearIframe();
targetmodal = '#printerInfoModal';
$('#modeliframe').attr("src", frametarget );
});
function blah(){debugger
var frametarget = $(this).attr('href');
targetmodal = '#printerInfoModal';
clearIframe();
$('#modeliframe').attr("src", frametarget );
}
function blah(frametarget){debugger
//var frametarget = $(this).attr('href');
targetmodal = '#printerInfoModal';
clearIframe();
$('#modeliframe').attr("src", frametarget );
}
function clearIframe() {
var iframe = $('#modeliframe');
var html = "";
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
}
This works, when I add the link manually; what I actually see when I click on the ajax-created link/button and select "inspect":
<a class="form-control btn btn-block extLink btn-success" id="printer10" style="margin-bottom: 5px;" href="http://1.2.3.4" data-toggle="modal" data-target="#printerInfoModal">Ready</a>
Can anyone see what am doing wrong or what I am missing?
So, if you are adding the button dynamically after the page loads, you'll need to target the document with your click handler like this:
$(document).on('click', '.extLink', function() {
// Do what you want when the button is clicked.
});
This is because when your page loads all of your Jquery handlers are attached to the DOM. If the element doesn't exist, then you are attaching them to nothing basically.

Modal Not Show Before ajax

I have an Javascript on click event that will loop all of the json to store it to database with ajax and before that i already add some modal to popup before the loop is running. but the problem is the modal doesn't pop up before the loop is running and pop up after the loop is running this is my code
this i my javascript
$.fn.dataTable.ext.buttons.Mapping = {
text: 'Save To Database',
action: function (e, dt, node, config) {
$('#modal-respondent-upload').modal('show');
var filename = $("#xlf").val().replace("C:\\fakepath\\", "");
var obj = jQuery.parseJSON(output);
$.each(obj.hasil, function (key, value) {
var dataRespondent = {
json: JSON.stringify(value),
importSessionDataID: 1
}
console.log(dataRespondent);
var respondentID = simpleAjaxRequest(dataRespondent, "/UploadExcel/CreateRespondent/", "Import Respondent Data");
});
}
};
function simpleAjaxRequest(data, url, text) {
var id = 0;
$.ajax({
type: 'POST',
url: url,
data: data,
async: false,
success: function (data) {
//moveProgressBar(10, text);
id = data;
}
});
return id;
}
and my modal is like this
<div class="modal fade" role="dialog" id="modal-respondent-upload">
<div class="modal-dialog">
<div class="modal-content">
<h1><span id="kondisi-data-modal">0</span>/<span id="jumlah-data-modal">0</span></h1>
</div>
</div>
</div>

Why I'm not able to print the error messages in AJAX response?

I've following HTML code:
<a href="#" id="promotion_status_1">
<button type="button" class="btn btn-default brmodalbtn" data-toggle="modal" data-target="#BrandImageModal" id="1">On</button>
</a>
<div class="container">
<div class="modal fade" id="BrandImgeModaal">
<div class="modal-dialog">
<div class="modal-content">
<form id="form" enctype="multipart/form-data" role="form">
<input type="text" class="form-control" name="brand_id" id="brand_id" value="{$data.id}">
<input type="text" name="admin_url" id="admin_url" value="http://localhost/abc.com">
<input type="text" name="op" value="upload_brand_image">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Brand Image</h4>
</div>
<div class="modal-body">
<div id="messages"></div>
<input type="file" name="file" id="file">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
jQuery AJAX Code :
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
//data : formdata ? formdata : form.serialize() + '&' + $.param({'op':'upload_brand_image'}),
contentType : false,
processData : false,
success: function(response) { alert(response); return;
if(response.error == 1) {
$('#BrandImageModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
},
dataType:"JSON"
});
e.preventDefault();
});
PHP Code:
$request = $_REQUEST ;
switch( $op ) {
case "upload_brand_image":
$ret = $objManufacturer->UploadBrandImage($request, $_FILES, $allowed_image_extension, $manuf_error_messages);
if(!$ret) {
$error_msg = $objManufacturer->GetAllErrors();
$response = array(
"error" => 1,
"error_message" => $error_msg
);
echo(json_encode($response));
} else {
if(!empty($_FILES['file']['name'])) {
upload_file_now( $_FILES['file'], $brand_image_path, $t, $brand_name, $ext);
}
}
die;
break;
}
The $error_msg array contains following content :
Array
(
[domain_id] => Please select domain
[brand_name] => Brand name can't be blank
[brand_name_invalid] => Brand name is not valid, it should be alphabetic
[email] => Brand email can't be blank
[email_invalid] => Brand email is not valid
[brand_image] => Brand image can't be blank
[brand_image_format] => Please upload brand image in a proper format
[brand_image_size] => Brand image size is greater than 5 MB
[brand_image_dimesnions] => Only upload brand image having dimensions >= 940 X 370 px
[details] => Brand details can't be blank
)
I'm not able to print the messages contained in this array in bootstrap modal.
Where I'm doing wrong? Would someone please help me in this regard?
Thanks
just change the success code...
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
//data : formdata ? formdata : form.serialize() + '&' + $.param({'op':'upload_brand_image'}),
contentType : false,
processData : false,
success: function (response) {
alert('successful : ' + response);
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
dataType:"JSON"
});
e.preventDefault();
});
Remember, json data is passed from server to broswer as text, in order to use it sensibly you need to convert it to a proper JSON object using $.parseJSON()
So try
success: function(response) {
response = $.parseJSON(response);
if(response.error == 1) {
Also modern browsers all have a javascript debugger associated with them. Get used to using it. Then you can set a breakpoint on the first line of the success: method and view the contents of the returned data, and pretty much everything else thats in scope as well.

Grails render gsp page after popup window

I have a popup window using twitter bootstrap, then I have a javascript that call a controller action. On that controller action I render a string to be displayed in the popup window. And on that action I have another render, It render the gsp page itself because a value is added in a textarea. How to make the second render work?
GSP:
<g:javascript>
function callEgCreate(){
$.ajax({
type: "GET",
url: "${createLink(controller: 'MGExecutingGroup', action: 'addEG_Create')}",
data: {
"inputField="+$("[name='inputField']").val()
"listField="+$("[name='listField']").val()
}
}).success(function(data) {
$('.modal-body').html(data);
$('#myModal').modal('show');
});
}
</g:javascript>
<g:textField name="inputField" />
<!-- Button to trigger modal -->
+
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Members</h3>
</div>
<div class="modal-body">
</div>
</div>
<textArea name="listField" id="listField" rows="50" cols="6" readonly>${params.Result}</textarea></td>
Controller:
def addEG_Create = {
def LdapName
def result
def membersString = ''
def members = ''
result = proxy.getWLSGroupParticipants(params.inputField)
if(result != null){
params.egId = params.id
LdapName = proxy.getWLSGroupsForUser(result[0])
int index
if (LdapName.size()>1){
index = 0
//find the index number for the correct Ldap name
for (int i = 0; i < LdapName.size(); i++) {
if (LdapName[i].toUpperCase() == params.inputField.toUpperCase()){
index = i
}
}
}else{
index = 0
}
if(params.listField.find(LdapName[index])){
params.Result = params.listField.trim()
membersString = params.listField.replace('\n',',')
flash.message = params.inputField + " exist in the list!"
}else{
flash.message = ""
if(params.listField!=''){
if(params.listField.charAt(params.listField.length()-1)=='\n'){
params.listField = params.listField.substring(0,params.listField.length()-1)
}
params.Result = params.listField.trim() + '\n' + LdapName[index].trim()
membersString = params.Result.replace('\n',',')
//membersString = params.listField.replace('\n',',') + LdapName[index]
} else{
params.Result = LdapName[index].trim()
membersString = LdapName[index]
}
}
for (int i = 0; i < result.size(); i++) {
if(i == 0){
members = result[i].trim()
}
else {
members = members + '\n' +result[i].trim()
}
}
params.Members = members
} else {
flash.message = params.inputField + " not found in LDAP. Please contact TECH CUST CARE"
params.Result = params.listField.trim()
membersString= params.listField.replace('\n',',')
//println "Not Found"
}
membersString = membersString.replace('\r','')
MGExecutingGroupInstance.members = membersString.trim()
render(members)
render(view:'create')
}
Jeka, you can't render two thinks like this
render(members)
render(view:'create')
the better way i see you can do this is something like this:
In your controller you can render your data as JSON:
def addEG_Create () {
...
...
render([members:members, openWin:'create'] as JSON)
}
And in your .gsp you should do shomething like this:
function callEgCreate(){
$.ajax({
type: "GET",
url: "${createLink(controller: 'MGExecutingGroup', action: 'addEG_Create')}",
data: {
"inputField="+$("[name='inputField']").val()
"listField="+$("[name='listField']").val()
},
dataType: 'json',
success(function(data) {
window.open(data['openWin']);
$('.modal-body').html(data['members']);
$('#myModal').modal('show');
});
}
I don't have tested this code, maybe it can have some errors, but the logic is this.
Updated
function callEgCreate() {
$.ajax({
type: "GET",
url: "testeChamada",
data: {"inputField": $("[name='inputField']").val(), "listField" : $("[name='listField']").val()},
dataType: 'json',
success: function (data) {
window.open(data['openWin']);
$('.modal-body').html(data['members']);
console.log(data['members']);
}
});
}
Ps1: In your controller when you say render render([members:members, openWin:'create'] as JSON) you have to receive the data in your page with the key of map [key:value]
Ps2: In your data: you have made a mistake. It should be a map with Key:Value

Categories

Resources