Open Jquery-UI Dialog Box inside table not showing in right place? - c#

Here is the jQuery Code to Show the Dialog Box Dynamically.
function ShowDialog(id) {
var x = $('btn_' + id).position();
$("#dialog_" + id).dialog({
title: "Description",
position:{ my:"" },
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
},
position:
{ my: "center", at: "center", of: window }
});
var theDialog = $("#dialog_" + id);
theDialog.dialog("open");
}
Here is Html Code for the gridview with generate dynamically.
<asp:TemplateField HeaderText="Description" ItemStyle-Width="80px">
<ItemTemplate>
<div id="dialog_1" style="display: none;">
<p>Details</p>
</div>
<button type="button" class="btn btn-success btn-sm btn_1" onclick="ShowDialog(1)">Show Detail</button>
</ItemTemplate>
</asp:TemplateField>
And Output is:
Should be open here

Try writing position: { my: "right center", at: "right center"} like this:
function ShowDialog(id) {
var x = $('btn_' + id).position();
$("#dialog_" + id).dialog({
title: "Description",
position:{ my:"" },
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
},
position:
{ my: "right center", at: "right center", of: window } // here
});
var theDialog = $("#dialog_" + id);
theDialog.dialog("open");
}

Related

No data returned when I incorporate dataTable in ASP.NET MVC

I am new to datatables. I am trying to incorporate datatable into an existing ASP.NET MVC application. Below is my Index.cshtml page. I tried to incorporate datatable in this code:
<table id="BookAssignmentTable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Office</th>
<th>Group</th>
<th>Updated By</th>
<th>Updated On</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#BookAssignmentTable").DataTable({
"ajax": {
"url": "/BookAssign/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Book" },
{ "data": "Office" },
{ "data": "Group" },
{ "data": "UpdatedBy" },
{ "data": "UpdatedOn" },
{
"data": "ID", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("StoreOrEdit", "bookAssignment_new")/" + data + "')><i class='fa fa-pencil'></i>Edit</a> <a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" + data + ")><i class='fa fa-trash'></i>Delete</a>";
},
"orderable": false,
"searchable": false,
"width" : "150px"
}
],
"language": {
"emptyTable" : "No data found please click on <b>Add New </b> Button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen : true,
resizable : false,
title : 'Fill Book Assignment Details',
height : 500,
width : 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
</script>
Below is my BookAssignController:
public ActionResult GetData()
{
using (ACREmployeeEntities db= new ACREmployeeEntities())
{
List<bookAssignment_new> bookList = db.bookAssignment_new.ToList<bookAssignment_new>();
return Json(new { data = bookList }, JsonRequestBehavior.AllowGet);
}
}
This is in my route.config file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "BookAssign", action = "Index", id = UrlParameter.Optional }
);
}
When I run my code, I see this URL, but I don't see any to data.
https://localhost:44374/BookAssign/Index
When I changed the url to
https://localhost:44374/BookAssign/getdata
the debugger stops at the getData method in the controller and returns the correct data. I am not sure what am I don't wrong and why I don't see any data.
Below is the screenshot:
For the first time appearance of .cshtml, you could do the following process:
First you should add <tbody></tbody> behind your <thead></thead> section.
In <tbody></tbody> section, you add a loop like this:
#for(var i = 0; i < yourData.ItsLength; i++)
{
<tr>
<td>yourData[i].YourFirstAttribute</td>
<td>yourData[i].YourSecondAttribute</td>
<td>yourData[i].YourThirdAttribute</td>
</tr>
}
P/S: I recommend you put your js script separately outside .cshtml file.

Pass jQuery grid value to c#

I would like to pass the studentID from the jQuery code to the C# code function when user clicks on the View link, please advise.
$(document).on("ready", function () {
obj = {
width: 940,
height: 555,
title: "Students List ",
};
obj.colModel = [
{
dataIndx: 7, editable: false, sortable: false, title: "Password", width: 65, align: "center", resizable: false, dataIndx: "studentID",
render: function (ui)
{
var rowData = ui.rowData, dataIndx = ui.dataIndx;
var val = rowData[dataIndx];
return "<a href='#" + rowData.studentID + "' style='text-decoration: underline;'>View</a>";
}, className: "checkboxColumn"
},
{ title: "Student Name", width: 220, getEditCellData: saveCell, dataIndx: "studentName" },
{ title: "Student ID", width: 120, getEditCellData: saveCell, dataIndx: "studentID" },
];
obj.dataModel = {
dataType: "JSON",
rPP: 20,
sortDir: "down",
rPPOptions: [1, 10, 20, 30, 40, 50, 100, 500, 1000],
filterIndx: "",
filterValue: ""
};
});
</script>
Grid
<asp:Content ID="Content2" ContentPlaceHolderID="PageTitlePlaceHolder" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<div id="grid_table" style="margin: auto;"></div>
</asp:Content>
Suggest changing your anchor tag to this
<a href="javascript:void(0);" data-studentId=rowdata.studentID style='text-decoration: underline;' class='viewStudent' >View</a>
After that wire up the click event in jquery for the view button
$(document).ready(function() {
$(".viewStudent").on("click", function() {
.. do what you need to do here ..
});
});
Here is a jsfiddle on how to do this
https://jsfiddle.net/8brpuo82/7/
Looks like you may be using web forms here - have you tried using a Hidden Field? Once you bind the anchor tag click event to a jQuery function:
ahh, I see GJohn beat me to it
... then you should be able to reference that ID within the Page response lifecycle, e.g., int studentID = hfStudentID.Value;

Jtable and MVC, doesn't load to view

I'm new to MVC and Jquery. Trying to use jtable, but nothing happens when loading page.
This is my view.
<link href="~/scripts/jtable.2.4.0/themes/metro/blue/jtable.css"
rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="~/scripts/jtable.2.4.0/jquery.jtable.js">
</script>
#using (Html.BeginForm("Upload", "Hotels", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div id="HotelsTable"> </div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jtable plugin
$('#HotelsTable').jtable({
title: 'List of Hotels',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: '#Url.Action("HotelsList")'
},
fields: {
Hotel1: {
title: 'Region',
width: '10%'
},
Hotel2: {
title: 'Hotel',
list: false,
width: '10%'
},
Hotel3: {
title: 'Desde',
type: 'date',
displayFormat: 'yy-mm-dd',
width: '8%',
list: false
},
Hotel4: {
title: 'Hasta',
type: 'date',
displayFormat: 'yy-mm-dd',
width: '8%'
},
Hotel5: {
title: 'Comentarios',
width: '8%',
}
}
});
//Load person list from server
$('#HotelsTable').jtable('load');
});
</script>
}
</body>
</html>
This is my control:
[HttpPost]
public JsonResult HotelsList()
{
try
{
List<Models.Models.HotelElem> hotels =
db.Database.Fetch<Models.Models.HotelElem>("SELECT * FROM Hotels");
return Json(new { Result = "OK", Records = hotels });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
While debugging it doesn't even go my HotelList() method. Need some help, what could it be?
Thanks!
Found solution! Maybe will be useful for someone.
Forgot to add
<script src="~/scripts/jquery-1.9.1.min.js"></script>
<script src="~/scripts/jquery-ui-1.9.2.min.js"></script>
...)

i am using j query pie chat in simple asp dot net page. how to bind value form database in j query pie chat

I am useing jquery pie chart in ASP.NET. pie chart doing work properly, but I want to bind values from database. How can I do bind database values in the pie chart. I have created a table in the database and I want to fetch values from database into the pie chart.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function ()
{
var chart;
$(document).ready(function ()
{
// Radialize the colors
Highcharts.getOptions().colors = $.map(Highcharts.getOptions().colors, function (color)
{
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
});
// Build the chart
chart = new Highcharts.Chart(
{
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function ()
{
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [
{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
}, ['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}
]
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<di v id="container" style="min-width: 400px; height: 400px; margin: 0 auto">
</div>
</body>
Simple solution would be to place your values from the DB in a hidden field and then access them using javascript and get their values to be used as part of the series.
This is the ASPX:
....
<asp:HiddenField ID="FireFoxDataValueFromDB" runat="server" />
<asp:HiddenField ID="IEDataValueFromDB" runat="server" />
....
This is the CS:
Page_Load Event()
{
if (!IsPostBack)
{
FireFoxDataValueFromDB = getFFDBValue();
IEDataValueFromDB = getIEDBValue
}
}
....
This is the Javascript:
var FFVal = $("#FireFoxDataValueFromDB").val();
var IEVal = $("#IEDataValueFromDB").val();
and then use it as the series data:
series: [
{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', FFVal],
['IE', IEVal],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
}, ['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}...

JQuery Dialog text area disappears on clicking on any other input

I am developing .NET MVC3 application in which I am using jquery dialog to display some text msg and text area together in pop up with OK Cancel button which is in a div "divForSentToCaseCommentLable". I am calling this dialog on button click "sentToCase".
chtml
<div id="divForSentToCaseComment">
<div id="divForSentToCaseCommentLable" style="display: none">
<b>
#Html.Raw("You are about to send the Alert to the Case Management queue and will be unable to make any further edits.")
<br />
#Html.Raw("Would you like to continue?")
</b>
<br />
#Html.Raw("Reason for status change:")
<br />
</div>
<div id="divShowCommentForStatusNDuedateChange" style="display: none">
#Html.TextArea("StatusDueDateChangeComment", new { #id = "StatusDueDateChangeComment", #name = "StatusDueDateChangeComment", String.Empty, #class = "text-box multi-line", #maxlength = "8000", #onkeypress = "return ImposeMaxLength(this,8000)", #onpaste = "return MaxLengthPaste(this,8000)" })
<div id="StatusCommentValidateMessage" style="display: none" />
</div>
</div>
JQuery
$("#sentToCase").click(function () {
if (isChanged && !isSubmit) {
var conf = confirm("The changes you made have not been saved. \nWould you like to continue?");
if (!conf) {
return false;
}
}
window.onbeforeunload = null;
$("#StatusDueDateChangeComment").val('');
$("#StatusCommentValidateMessage").hide();
$("#divShowCommentForStatusNDuedateChange").show();
$("#divForSentToCaseCommentLable").show();
$('#divForSentToCaseComment').dialog({
autoOpen: false,
resizable: true,
width: 415,
height: 300,
modal: true,
fontsize: 10,
title: 'Reason for send to case',
buttons: {
"Ok": function () {
// var sendToCaseAnswer = confirm("You are about to send the Alert to Cases and will be unable to make any further edits. Would you like to continue?");
// if (sendToCaseAnswer) {
var reasonForClear = $("#StatusDueDateChangeComment").val();
var incidentId = $("#IncidentID").val();
if (validateSatusComment(reasonForClear, "SentToCase")) {
$.blockUI({ message: '<h2><img src="../../Content/images/spinner.gif" />Loading ...</h2>' });
$.ajax({
type: "GET",
data: { incidentId: incidentId, reasonForClear: reasonForClear },
//url: '/Bamplus/AlertAndCaseManager/Alert/SendToCaseStatus',
url: sendToCaseStatusJsonUrl,
dataType: "json",
cache: false,
contentType: "application/json",
success: function (data) {
if (data.redirectTo != null) {
window.location = data.redirectTo;
$.unblockUI({ fadeOut: 200 });
} else {
$('#Messages').show(400);
$("#Messages").html(data.Html);
$.unblockUI({ fadeOut: 200 });
}
},
error: function () {
$.unblockUI({ fadeOut: 200 });
}
});
// }
$(this).dialog("close");
}
},
Cancel: function () {
$(this).dialog("close");
}
}, open: function () {
$('.ui-dialog-buttonpane').find('button:contains("Cancel")').removeClass().addClass("Button");
$('.ui-dialog-buttonpane').find('button:contains("Ok")').removeClass().addClass("Button");
}
});
$("#divForSentToCaseComment").dialog("open");
return false;
});
There is another button "watching" which is calling "divShowCommentForStatusNDuedateChange" div in dialog box to display only text area with Ok Cancel button
JQuery:
$("#watching").click(function () {
if (isChanged && !isSubmit) {
var conf = confirm("The changes you made have not been saved. \nWould you like to continue?");
if (!conf) {
return false;
}
}
window.onbeforeunload = null;
$('#divShowCommentForStatusNDuedateChange').dialog({
autoOpen: false,
resizable: false,
width: 350,
height: 220,
modal: true,
fontsize: 10,
title: 'Reason for status change',
buttons: {
"Ok": function () {
var reasonForClear = $("#StatusDueDateChangeComment").val();
var incidentId = $("#IncidentID").val();
if (validateSatusComment(reasonForClear, "Watching")) {
$.blockUI({ message: '<h2><img src="../../Content/images/spinner.gif" />Loading ...</h2>' });
$.ajax({
type: "GET",
data: { incidentId: incidentId, reasonForClear: reasonForClear },
//url: '/Bamplus/AlertAndCaseManager/Alert/WatchingStatus',
url: watchingStatusJsonUrl,
dataType: "json",
cache: false,
contentType: "application/json",
success: function (result) {
if (result.redirectTo != null) {
window.location = result.redirectTo;
$.unblockUI({ fadeOut: 200 });
} else {
$('#Messages').show(400);
$("#Messages").html(result.Html);
$.unblockUI({ fadeOut: 200 });
}
},
error: function () {
$.unblockUI({ fadeOut: 200 });
}
});
$(this).dialog("close");
}
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function () {
$('.ui-dialog-buttonpane').find('button:contains("Cancel")').removeClass().addClass("Button");
$('.ui-dialog-buttonpane').find('button:contains("Ok")').removeClass().addClass("Button");
}
});
$("#StatusDueDateChangeComment").val('');
$("#StatusCommentValidateMessage").hide();
$("#divShowCommentForStatusNDuedateChange").dialog("open");
return false;
});
Problem-
scenario 1:
on page load I click on "watching" button to display "watching pop-up" with only
text area and "OK Cancel button", which is perfect.
Then I press "Cancel button" from "watching pop-up" which will hide "watching pop-up"
Now I go for "sentToCase" button from main page to display "sentToCase pop-up" with text message and text area.
I found that text area is not rendering in "sentToCase pop-up", I can only see text message in "sentToCase pop-up".
scenario 2:
On first page load if I directly click on "sentToCase" button then, "sentToCase pop-up" correctly renders text message and text area with "OK cancel button" which is correct.
I found solution for this problem by referring this post
jquery ui dialog box removes <div> after closing
The problem here is that you have your dialogs nested. The way jQuery dialog works is that it assumes all dialogs must be exclusive. Do not nest your dialogs, and you should be ok.
after separating div's existing code works fine. I done it like this
<div id="divForSentToCaseComment">
<div id="divForSentToCaseCommentLable" style="display: none">
<b>
#Html.Raw("You are about to send the Alert to the Case Management queue and will be unable to make any further edits.")
<br />
#Html.Raw("Would you like to continue?")
</b>
<br />
#Html.Raw("Reason for status change:")
<br />
</div>
<div id="divShowCommentForStatusNDuedateChangeSendToCase" style="display: none">
#Html.TextArea("StatusDueDateChangeComment", new { #id = "StatusDueDateChangeCommentSendTocase", #name = "StatusDueDateChangeComment", String.Empty, #class = "text-box multi-line", #maxlength = "8000", #onkeypress = "return ImposeMaxLength(this,8000)", #onpaste = "return MaxLengthPaste(this,8000)" })
<div id="StatusCommentValidateMessageSendToCase" style="display: none" />
</div>
</div>
<div id="divShowCommentForStatusNDuedateChange" style="display: none">
#Html.TextArea("StatusDueDateChangeComment", new { #id = "StatusDueDateChangeComment", #name = "StatusDueDateChangeComment", String.Empty, #class = "text-box multi-line", #maxlength = "8000", #onkeypress = "return ImposeMaxLength(this,8000)", #onpaste = "return MaxLengthPaste(this,8000)" })
<div id="StatusCommentValidateMessage" style="display: none" />
</div>
but because of separate divs I need to do some extra efforts on validation an all.
Thank you

Categories

Resources