Dialog reloading Partial - JQuery doesn't work (MVC 3) - c#

When I open dialog all things work correct but when I close dialog and I try open this again I have got problem with JQuery (animation, hide etc.) Probably Partial View all the time is working and when dialog is showed again it doesn't mean Partial View is also new. How to fix it?
This doesn't work
<script type="text/javascript">
$('#bladReje').hide();
$('#bladRejeText').hide();
$('#poprawnieReje').hide();
$('#poprawnieRejeText').hide();
</script>
Partial
data.View
AJAX
$.ajax({
url: '#Url.Action("Reje", "Log")',
dataType: "json",
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
var el1 = $('<div><strong style="color: black">' + data.View + '</strong></div>');
$(el1).dialog(
{
modal: true,
title: '<div></div>',
minWidth: 340,
minHeight: 300,
buttons: {
'close': function () {
$(this).dialog("destroy");
}
}
});
}
}
});
});
This is example of my Partial View
<div id="bladReje" style="padding: 0px; width: 100%; margin: 0 auto; padding: 0 auto; text-align: left;
font-family: arial; visibility:hidden;">
<div id="bladRejeText" style="font-size: 16px; visibility:hidden;">
</div>
</div>
#Html.TextBoxFor(m => m.Example, new { style = "width:220px" })
<input type="button" class="button" value="Zapisz" onclick="SaveRejestracja();" style="float: right; margin-right: 30px;"/>
<script type="text/javascript">
$('#bladReje').hide();
$('#bladRejeText').hide();
</script>
<script type="text/javascript">
function SaveRejestracja() {
var Example = $('#Example').val();
$.ajax({
url: '#Url.Action("Example", "ControllerExample")',
dataType: "json",
data: {
Nick: Example
},
type: "POST",
traditional: true,
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
$('#bladReje').hide();
$('#bladReje').css({ visibility: "hidden" });
$('#bladRejeText').hide();
$('#bladRejeText').css({ visibility: "hidden" });
}
if (!data.Success) {
$('#bladReje').hide();
$('#bladReje').css({ visibility: "visible" });
$('#bladRejeText').hide();
$('#bladRejeText').css({ visibility: "visible" });
}
}
});
}
</script>
This work only first time
<script type="text/javascript">
$('#bladReje').hide();
$('#bladRejeText').hide();
</script>

Related

C# MVC ajax call to database with a popup model does not recognize cancel button click

I have a c# application which displays a webgrid populated by a database. When I double click on a grid element, jquery captures the double click, determines the row of the grid, finds the ID column and does an ajax call to pass the ID back to my controller. Ajax is instructed to expect html as the response.
When the controller receives the ID from the view, it reads the record from the database with that ID, populates a list with a set of fields, and passes that list as a parameter to a partial view.
The partial view returns html to the ajax call. The html includes a form where the database fields are displayed in text boxes so the user can update the data. There is a submit button and a cancel button at the bottom of the form.
The is the ajax code:
$("body").on("dblclick", "#WebGrid td", function () {
var row = $(this).closest("tr");
var FirstName = row.find("td").eq(1).text();
var LastName = row.find("td").eq(2).text();
var ID = row.find("td").eq(0).text();
$.ajax({
url: "/Home/Details",
type: "POST",
data: { ID: ID, FirstName: "", LastName: "", EmailAddress: "", EmailType: "" },
dataType: "html",
success: function (result) {
$('#dialog').html(result);
$('#dialog').dialog('open');
},
failure: function (result) {
alert("FAILURE " + result.responseText);
},
error: function (result) {
alert("ERROR " + result.responseText);
}
});
return false;
});
And this is how I define the division that the returned html gets placed into:
<div id="dialog" style="display: none">
</div>
And this is the function that I have:
$(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "Update"
});
});
When I run the application, and I double click on a grid item and the partial view gets passed back to the ajax call, the dialog division gets displayed correctly with the data from the database.
The problem is when I click on the Cancel button nothing happens. And I do not get the 'cancel button clicked' message on the console. I have this code to capture the click of the cancel button:
$("#btnCancel").on('click', function (event) {
console.log("cancel button clicked");
$('#dialog').hide;
toastr.warning("Your update has been cancelled");
clear();
display();
});
Any suggestions? Thank you.
edit:
Here is the entire code of the initial View where the grid is rendered:
#model List<CodingChallengeV4.ViewModels.ContactPassData>
#{
ViewBag.Title = "UpdateAllData";
}
#{
Layout = null;
WebGrid grid = new WebGrid(source: Model, canPage: true, canSort: false);
}
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js">
</script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<!-- Latest compiled JavaScript -->
<!-- add thids links for the error message-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
<style type="text/css">
.Grid {
border: 1px solid #ccc;
border-collapse: collapse;
}
.Grid th {
background-color: #F7F7F7;
font-weight: bold;
}
.Grid th, .Grid td {
padding: 5px;
width: 150px;
border: 1px solid #ccc;
}
.Grid, .Grid table td {
border: 0px solid #ccc;
}
.Grid th a, .Grid th a:visited {
color: #333;
}
</style>
<h2>Update All Contacts</h2>
#grid.GetHtml(
htmlAttributes: new { #id = "WebGrid", #class = "Grid" },
columns: grid.Columns(
grid.Column(header: "", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedID">#item.passedID</div></text>),
grid.Column(header: "First Name", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedfName">#item.passedfName</div></text>),
grid.Column(header: "Last Name", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedlName">#item.passedlName</div></text>),
grid.Column(header: "eMail Address", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedeMail">#item.passedeMail</div></text>),
grid.Column(header: "eMail Type", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedeMailTypeString">#item.passedeMailTypeString</div></text>)
)
)
<div id="dialog" style="display: none;" >
</div>
<script>
$(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "View Details"
});
});
$(document).ready(function () {
$('#toast-container').find('.toast-top-center').removeClass('.toast-top-center');
toastr.options = {
"closeButton": true,
'autoWidth': false,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-center-center",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
$("#btnCancel").on('click', function (event) {
console.log("cancel button was clicked");
$('#dialog').dialog('hide');
toastr.warning("Your update has been cancelled");
clear();
display();
});
$("body").on("dblclick", "#WebGrid td", function () {
var row = $(this).closest("tr");
var FirstName = row.find("td").eq(1).text();
var LastName = row.find("td").eq(2).text();
var ID = row.find("td").eq(0).text();
$.ajax({
url: "/Home/Details",
type: "POST",
data: { ID: ID, FirstName: "", LastName: "", EmailAddress: "", EmailType: "" },
dataType: "html",
success: function (result) {
$('#dialog').html(result);
$('#dialog').dialog('open');
},
failure: function (result) {
alert("FAILURE " + result.responseText);
},
error: function (result) {
alert("ERROR " + result.responseText);
}
});
return false;
});
});
</script>

Invalid JSON primitive: Date

I keep getting the following error: "Invalid JSON primitive: Date". I am not sure how to correct as I have changes to the front/back-end of the project. Everything seems to be working other than when I de-bug the JavaScript. My front-end code is as follows (I only included some HTML, where a date is used):
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent"
runat="server">
<script>
$("#Grid").kendoGrid({
"dataSource": {
"transport": {
"read": {
"url": "CreateReq.aspx/PopulateMessages",//page then function
contentType: "application/json; charset=utf-8",
type: "GET",
dataType: "json",
"data": {
requestID: document.getElementById("lblRequestID").textContent
}
},
create: {
url: "CreateReq.aspx/CreateMessage",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
"data": {
}
},
"prefix": ""
},
"schema": {
data: function (response) {
return response.d;
},
model: {
fields: {
Date: { type: "date",editable: false, format: "{0: MM/dd/yyyy}", encoded: true, /*defaultValue: Date.now*/ },
Author: { type: "string", editable: true},
Message: { type: "string" },
}
}
},
},
//pageable: true,
height: 225,
toolbar: ["create"],
columns: [
{ field: "Date", title: "Date", width: "75px", /*template: '#= kendo.toString((Date), "MM/dd/yyyy")#'*/ format: "{0: MM/dd/yyyy}", encoded: true},
{ field: "Author", title: "Author", width: "75px" },
{ field: "Message", title: "Message", width: "300px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "inline"
});
});
</script>
<h1 style="text-align: center">Academic Code Request</h1>
<div class="TopPageButtons" style="text-align: center">
<br />
</div>
<div class="TrackingBox">
<div class="TrBoxContent">
<div>
<label><b>ID</b></label><br />
<asp:Label ID="lblRequestID" Text="" runat="server" ClientIDMode="Static"/>
</div>
<div>
<label><b>Form View Date</b></label><br />
<asp:TextBox ID="RequestDate" runat="server" ClientIDMode="Static" style="text-align:center"/>
<script>
document.getElementById("RequestDate").value = new Date().toString();
</script>
</div>

Jssor Sliders transition is not working

I'm using Jssor sliders,My web method returns 2 image URL & Ajax success function get it correctly.But Transition is not working & only 1st image show.
Html & Css part
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px; height: 300px;">
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 600px; height: 300px; overflow: hidden;">
<div id="HomeImgSliders"> </div>
<%-- <div><img u="image" src="http://jssor.com/img/photography/003.jpg" /></div>-->
</div>
<!-- Arrow Navigator Skin Begin -->
<style>
/* jssor slider arrow navigator skin 03 css */
/*
.jssora03l (normal)
.jssora03r (normal)
.jssora03l:hover (normal mouseover)
.jssora03r:hover (normal mouseover)
.jssora03ldn (mousedown)
.jssora03rdn (mousedown)
*/
.jssora03l, .jssora03r, .jssora03ldn, .jssora03rdn {
position: absolute;
cursor: pointer;
display: block;
background: url(http://jssor.com/img/a17.png) no-repeat;
overflow: hidden;
}
.jssora03l {
background-position: -3px -33px;
}
.jssora03r {
background-position: -63px -33px;
}
.jssora03l:hover {
background-position: -123px -33px;
}
.jssora03r:hover {
background-position: -183px -33px;
}
.jssora03ldn {
background-position: -243px -33px;
}
.jssora03rdn {
background-position: -303px -33px;
}
</style>
<!-- Arrow Left -->
<span u="arrowleft" class="jssora03l" style="width: 55px; height: 55px; top: 123px; left: 8px;"></span>
<!-- Arrow Right -->
<span u="arrowright" class="jssora03r" style="width: 55px; height: 55px; top: 123px; right: 8px"></span>
<!-- Arrow Navigator Skin End -->
<a style="display: none" href="http://www.jssor.com">jQuery Slider</a>
Here is my Jquery & JSON /Ajax Call Part
<script>
$(function () {
LoadHomeImageSliders();
});
jQuery(document).ready(function ($) {
var options = {
$DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
$AutoPlay: true,
$ArrowNavigatorOptions: { //[Optional] Options to specify and enable arrow navigator or not
$Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 0, //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1
$AutoPlay: true
}
};
var jssor_slider1 = new $JssorSlider$("slider1_container", options);
});
function LoadHomeImageSliders() {
debugger;
var url = '<%= ResolveUrl("~/WebMethods.aspx/GetHomeImageSliders") %>';
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
var html = "<img u=image src=" + value.ImagePath + "/>";//<-- Image Path/paths comes here Correctly
$("#HomeImgSliders").append(html);
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
Before initialize jssor slider, you'd get slides html well populated.
reference: Jssor - how to add slides dynamically?
<script>
jQuery(document).ready(function ($) {
LoadHomeImageSliders();
});
function LoadHomeImageSliders() {
debugger;
var url = '<%= ResolveUrl("~/WebMethods.aspx/GetHomeImageSliders") %>';
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
var html = "<img u=image src=" + value.ImagePath + "/>";//<-- Image Path/paths comes here Correctly
$("#HomeImgSliders").append(html);
});
var options = {
$DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
$AutoPlay: true,
$ArrowNavigatorOptions: { //[Optional] Options to specify and enable arrow navigator or not
$Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 0, //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1
$AutoPlay: true
}
};
var jssor_slider1 = new $JssorSlider$("slider1_container", options);
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
</script>

jQuery sortable: How to properly post element id array?

question:
I am working with jQuery sortable.
I used this tutorial:
http://www.xmech.net/programming/jquery-ui-sortable-tutorial/
Now this gives me a string like:
ID[]=2&ID[]=3&ID[]=4&ID[]=1
or even worse, when I call the id's IDa_1, IDb_2, IDc_3, IDd_4 it gives me
IDb[]=2&IDc[]=3&IDd[]=4&IDa[]=1
I find this format maximum horrible and unuseful...
I want just pages : ["IDb_2", "IDc_3", "IDd_4", "IDa_1"]
and have the order of the element in the array index.
To rectify this, I did:
var xxx = { pages: $(this).sortable('toArray') };
alert(JSON.stringify(xxx));
This is my home controller:
public string SaveSortable(string pages)
{
string strPages = Request.Params["pages"];
Console.WriteLine(pages);
return pages;
}
public ActionResult Sortable()
{
return View();
} // End Action Sortable
The problem is, both "pages" and strPages is always null...
It gets into the right controller though...
What am I doing wrong ?
This is my .cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<style type="text/css" media="all">
html {margin: 0px; padding: 0px; height: 100%;}
body {margin: 0px; padding: 0px; height: 100%;}
input{margin: 0px; padding: 0px; }
</style>
<style type="text/css" media="all">
.menu li
{
list-style: none;
padding: 10px;
margin-bottom: 5px;
border: 1px solid #000;
background-color: #C0C0C0;
width: 150px;
display: inline;
}
</style>
<script type="text/javascript" src="#Url.Content("~/Scripts/jQuery/jquery-1.7.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jQuery/jquery-ui/1_8_21/js/jquery-ui-1.8.21.custom.min.js")"></script>
<script type="text/javascript" language="javascript">
Date.prototype.getTicksUTC = function () {
return Date.parse(this.toUTCString()) + this.getUTCMilliseconds();
} // End Function getTicksUTC
var tickURL = '#Url.Content("~/Scripts/jQuery/SlickGrid/images/tick.png")';
$(document).ready(function () {
//$('#menu-pages').sortable();
$("#menu-pages").sortable({
update: function (event, ui) {
alert("posting");
//var ElementsOrder = $(this).sortable('toArray').toString();
var ElementsOrder = $(this).sortable('toArray');//.toString();
//alert(JSON.stringify(ElementsOrder));
var xxx = { pages: $(this).sortable('toArray') };
//alert(JSON.stringify(xxx));
//document.writeln("<h1>"+ JSON.stringify(xxx) + "</h1>");
// $.post("#Url.Action("SaveSortable", "Home")?no_cache=" + new Date().getTicksUTC(), { pages: $('#menu-pages').sortable('serialize') });
// $.post("#Url.Action("SaveSortable", "Home")?no_cache=" + new Date().getTicksUTC(), { pages: $('#menu-pages').sortable('serialize', { key: 'id' }) });
$.post("#Url.Action("SaveSortable", "Home")?no_cache=" + new Date().getTicksUTC(), { pages: $(this).sortable('toArray') });
}
});
});
</script>
</head>
<body>
<ul class="menu" id="menu-pages">
<li id="ID_1">Home</li>
<li id="ID_2">Blog</li>
<li id="ID_3">About</li>
<li id="ID_4">Contact</li>
</ul>
</body>
</html>
Simply use a JSON request:
$('#menu-pages').sortable({
update: function (event, ui) {
$.ajax({
url: '#Url.Action("SaveSortable", "Home")',
type: 'POST',
cache: false,
contentType: 'application/json',
data: JSON.stringify({ pages: $(this).sortable('toArray') }),
success: function(result) {
// ...
}
});
}
});
and then:
[HttpPost]
public ActionResult SaveSortable(string[] pages)
{
// pages will contain what you need => a list of ids
...
}
For the record, here's how the JSON request POST payload will look like:
{"pages":["ID_2","ID_3","ID_1","ID_4"]}

On select Row doesn't activate event in jqgrid

I have a jqGrid on which clicking of a row should render a partial view below the jqGrid, but it doesn't happen. I am doing something as shown below:
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.jqGrid.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/json2.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/CookieManagement.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jQGridState.js")"></script>
<link href="#Url.Content("~/Content/jquery.jqGrid/ui.jqgrid.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$('#Listing').jqGrid({
url: '#Url.Action("Grid", "Name")',
datatype: "json",
edit: false,
add: false,
del: false,
height: 330,
mtype: 'GET',
colNames: ['ID','Name'],
jsonReader: {
root: "Clients",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
cell: "",
id: "0"
},
colModel: [
{ name: 'Id', index: 'Id', width: 65, align: 'center', sorttype: "int" },
{ name: '#NameMap.STATUS_COLUMN', index: '#NameMap.STATUS_COLUMN', width: 140, align: 'left', sortable: true }],
pager: '#pager',
rowNum: 10,
rowList: [10, 15, 20],
sortname: 'Id',
sortorder: 'asc',
viewrecords: true,
gridview: true,
onSelectRow: function (id) {
$.ajax({
url: '#Url.Action("Details","Name")',
data: { 'Id': id },
success: function (detailsHtml) {
$('#NameDetails').html(detailsHtml);
},
dataType: 'html'
});
},
loadComplete: function () {
$('#NameDetails').html("");
}
});
});
});
</script>
Here Details and Grid are the controller action in the Name Controller. Details which is hooked up to onSelectRow returns a View and $('#NameDetails') is the id of the last div in this page.
My problem is that I am not able to see the details view appearing even though the values inside it are properly getting populated, is there something wrong in my OnSelectRow or do i need to include any other javascript file??
Well that was foolish, but actually I did a spelling mistake in an id called "NameDetails" as "NameDetalis" and that was the reason that my view was not getting rendered.

Categories