JQuery Dialog text area disappears on clicking on any other input - c#

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

Related

Unable set handler URL of C#

Currently i'm working on flowplayer with nimble streaming , i'm returning Url from handler.
By setting up src to handler is successfully redirect to handler but flowplayer is not able to setting up return output of handler(i.e. handler is returning m3u8 URL)..below is the example code
<div>
<input type="button" id="Test" value="click" />
</div><br />
<div>
<input type="button" id="Test2" value="click2" />
</div><br />
<script>
$(function () {
var api = flowplayer("#player", {
splash: true,
embed: { skin: "//releases.flowplayer.org/7.0.2/skin/skin.css" },
ratio: 9 / 16,
seekable: true,
clip: {
live: false,
autoplay: false,
sources: [
{
type: "application/x-mpegurl",
src: "http://xx.xx.xx.xx:8081/videos/fast.mp4/playlist.m3u8"
}
]
},
onload: function () {
alert("player loaded.");
},
})
$("#Test").click(function () {
flowplayer().load("http://xx.xx.xx.xx:8086/vod/edge/camera2/profile16/camera2_profile16_2017-03-02_055323.mp4/playlist.m3u8");
})
$("#Test2").click(function () {
flowplayer().load("http://xx.xx.xx.xx:8081/ProxyDemo/ReverseProxy.ashx");
})
})
</script>

How to perform searching in autofill on textbox with single enter press

<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" ></asp:TextBox>
</div>
<br>
<script type="text/javascript">
$(function fnc() {
$(".search_hot_txtbox").autocomplete({
source: function(request, response) {
$.ajax({
url: "hotel-result.aspx/BindDatatoDropdown",
data: "{ 'cn': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.HotelName
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
protected void chk3_CheckedChanged(object sender, EventArgs e)
{
if (Session["List"] != null)
UCPager1.GetItemsControl(1, 5, 0, chk3star.Checked, chk2star.Checked, chk1star.Checked, chk4star.Checked, chk5star.Checked, chkP1.Checked, chkP2.Checked, chkP3.Checked, chkP4.Checked, chkP5.Checked, txtHotel.Text, spP1.InnerText, spP2.InnerText, spP3.InnerText, spP4.InnerText, spP5.InnerText, new Repeater(), chkP6.Checked, chkP7.Checked, chkP8.Checked, spP6.InnerText, spP7.InnerText, spP8.InnerText);
else
UCPager1.GetItems();
}
You need here to make a post back, when you press "enter" on the textbox the browser make the postback, but if you wish to make it with javascript you need to fire up a button control.
So I place a button control, and I can even have it hidden with css as:
<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" onkeydown="return SendKeyEnterTo(event, 'btnGo');" />
<asp:Button runat="server" ID="btnGo" Text="search" onclick="btnSearch_Click" style="display:none;" ClientIDMode="Static" />
</div>
and then using this simple javascript I read the "enter" key from the textbox and trigger that post back of the input control.
function SendKeyEnterTo(e, IdToClick)
{
// look for window.event in case event isn't passed in
if (window.event)
{
e = window.event;
}
if (e.keyCode == 13)
{
document.getElementById(IdToClick).click();
return false;
}
else
{
return true;
}
}
This onkeydown="return SendKeyEnterTo(event, 'btnGo');" is important to read the text box input, and the ClientIDMode="Static" on the button is important to keep the same id when its rendered.
Also, please note, this code is run together with the autocomplete, and I have tested and use it.

Ajax.abort() not working

I have read a lot of pages explaining how ajax.abort() should work but for some reason I cannot get this to work with my situation. Here is the code I have:
<script type="text/javascript">
$(document).ready(function () {
...
function abortxhRequest() {
xhRequest.abort();
}
var xhRequest
function SendFileToServer(blob, fileName) {
if (xhRequest) {
xhRequest.abort();
}
xhRequest = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
//Do something with upload progress
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
progressBar.css("width", percentLoaded + '%');
progressPercentage.text(percentLoaded + '%');
}
}, false);
//Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
//Do something with download progress
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
progressBar.css("width", percentLoaded + '%');
progressPercentage.text(percentLoaded + '%');
}
}, false);
return xhr;
},
type: "POST",
url: "myPage.aspx/SendFileToServer",
data: "{blob: \"" + blob + "\", fileName: \"" + fileName + "\"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// If there was no data show No Data display
if (msg.d == "success") {
$("#spManagePhoto").html("Complete!");
setTimeout(function () {
$("#divManagePhotoTakePhoto").show();
$("#divManagePhotoUploading").hide();
}, 2000);
}
},
error: function (xhr, status, thrownError) { //Something went wrong on front side
alert(xhr.responseText); //You don't want to read all that, lol
//alert(thrownError); //Right down to the point
}
});
}
});
...
</script>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
...
<div id="divManagePhotoUploading">
<center>
<div class="marginTop10"><span id="spManagePhoto" class="SubmittingText"></span></div>
<div class="marginTop20"><img src="Images/ajax-loader.gif" alt="Loading..." /></div>
</center>
<div id="divProgressBarShell" class="ui-corner-all">
<div style="margin:5px; position:relative">
<div id="progress_bar">
<table border="0" cellpadding="0" cellspacing="0" style="width:100%; height:100%"><tr align="center"><td valign="middle">
<div class="percent"></div>
<label class="PercentLabel">0%</label>
</td></tr></table>
</div>
</div>
</div>
<div>
<button onclick="abortxhRequest();" class="nav-button2" style="display:block">Cancel Upload</button>
</div>
</div>
...
</asp:Content>
When I click the Cancel Upload button, ajax throws an error. Status of the error is "error" and xhr.responseText is blank. What am I doing wrong? Any help with this is greatly appreciated.
Abort() triggers the error() in Ajax. This is JQuery's standard behavior.
Do this to detect error but not abort:
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus != "abort") { // aborting actually triggers error with textstatus = abort.
alert(errorThrown.message);
}
}
Here is a reference of this behavior:
http://paulrademacher.com/blog/jquery-gotcha-error-callback-triggered-on-xhr-abort/

Display a message after file upload in Ajax.BeginForm

How to display a message from “return json(message)” of action in jquery dialog after posting its form. I tried with the following, everything works fine, but return JsonResult triggering Save/Open prompt instead of OnSuccess call with Ajax.BeginForm.
Partial View:
#using (Ajax.BeginForm("SaveDetails", "FileManage", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnFileUploadSuccess" }, new { enctype = "multipart/form-data", id = "myForm" }))
{
<input id="fuMyFile" type="file" name="files" />
<input id="btnSubmit" type="submit" value="Submit" />
}
<div id="dialogboxWin" style="display: none; padding: 8px 15px;">
<div id="dvWindow"></div>
</div>
Following is the jQuery code:
$('#btnSubmit').click(function () {
$("#dvWindow").html("Are you sure to submit?");
$("#dialogboxWin").dialog({
modal: true,
width: 400,
autoOpen: true,
title: 'Confirmation',
buttons: {
"Yes": function () {
$(this).dialog("close");
$('#myForm).submit();
},
"No": function () {
$(this).dialog("close");
}
}
});
return false;
});
function OnFileUploadSuccess(data) {
alert(data.Message);
}
Controller Action Method:
[HttpPost]
public JsonResult SaveDetails(HttpPostedFileBase file)
{
bool isSaved = File Saving & Some DB operations
return Json(new
{
Result = isSaved
Message = (isSaved)?"Saved Successfully." : "Failed"
}, JsonRequestBehavior.AllowGet);
}
As you are submitting the form you don't get the message returned from the action.You can save the message you want to show in some session variable and check whether the session variable contains any value or not in document ready of the page and show message accordingly.

Reloading partial page after jQuery ajax command

I am very new to both JQuery and Asp.net MVC 3 (C#), so I apologize if this is trivial. I have an MVC partial view (Index.cshtml) that has a list of tasks. These tasks are contained within indivudal divs that I have in a list style layout. I have a button called "add task" that opens a dialog. This dialog will save the added task to the database via an AJAX Json call to the controller.
This is where I am having trouble - after the dialog closes I would like the list of tasks to reload with the task i just added. I have found examples where the entire page is reloaded, and I found examples where the controller is supposed to return a rendered view. My problem is that the dialog is being opened from the partial I want to reload. Is there a way to accomplish what I am trying to do.
Index.cshtml
#model IEnumerable<TaskManagementApplication.Models.Project>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="ProjectAccordionWrapper">
#foreach (var item in Model)
{
<div class="ProjectWrapper">
<h3>#item.Name</h3>
<div class="column">
<button class="createTaskButton" id="#item.ProjectID">Create New Task</button>
#foreach(var task in item.Tasks) {
var buttonClass = "taskID" + task.TaskID;
<div class="portlet">
<div class="portlet-header">#task.TaskName</div>
<div class="portlet-content">#task.TaskDescription</div>
<button class="editTaskButton" id="#task.TaskID">Edit Task</button>
</div>
}
</div>
</div>
}
</div>
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="TaskName">Task Name</label>
<input type="text" name="TaskName" id="name" class="text ui-widget-content ui-corner-all" />
<label for="TaskDescription">Task Description</label>
<input type="text" name="TaskDescription" id="description" value="" class="text ui-widget-content ui-corner-all" />
<input type="hidden" name="TaskID" id="ID" />
<input type="hidden" name="ProjectID" id="ProjectID" />
</fieldset>
</form>
</div>
Partial Javascript
function GetTask(id) {
if (id.length > 0) {
$.ajax({
url: '/Project/GetTaskFromID',
type: "POST",
data: { "id": id },
success: PopulateDialogFields,
error: HandleError
});
}
}
function PopulateDialogFields(data) {
$("#name").val(data.TaskName);
$("#description").val(data.TaskDescription);
$("#ID").val(data.TaskID);
}
function HandleError(data) {
alert(data.error);
var foo = data;
}
function SaveTask() {
var taskName = $("#name").val();
var taskDescription = $("#description").val();
var id = $("#ID").val();
var projectID = $("#ProjectID").val();
if (id.length > 0) {
$.ajax({
url: '/Project/SaveTask',
type: "POST",
data: { "taskName": taskName, "taskDescription": taskDescription, "taskID": id }
});
}
else {
$.ajax({
url: '/Project/SaveTask',
type: "POST",
data: { "taskName": taskName, "taskDescription": taskDescription, "projectID": projectID }
});
}
}
$("#dialog-form").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"OK": function () {
SaveTask();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
allFields.val("").removeClass("ui-state-error");
window.location.reload(true);
},
open: function () {
var id = $(this).data("id");
var projectID = $(this).data("projectID");
$("#ProjectID").val(projectID);
var button = $("#" + id);
GetTask(id);
}
});
$(".editTaskButton")
.button()
.click(function () {
$("#dialog-form").data('id', this.id).dialog("open");
});
$(".createTaskButton")
.button()
.click(function () {
$("#dialog-form").data('projectID', this.id).dialog("open");
});
I am relatively new to jQuery and ASP.NET MVC as well, however, here's what first comes to mind.
In order to maintain the AJAX-y aspect of the page, I suggest that you create a method that handles a POST which returns a JSON formatted set of TaskManagementApplication.Models.Project. This method can optionally return filtered results.
The markup would look like this,
<div id="ProjectAccordionWrapper">
<div id="ProjectWrapperTemplate" class="ProjectWrapper" style="display: none;">
<h3 id="itemName"></h3>
<div class="column">
<button class="createTaskButton" id="itemProjectID">Create New Task</button>
<div id="portletTemplate" class="portlet">
<div class="portlet-header" id="taskName"></div>
<div class="portlet-content" id="taskDescription"></div>
<button class="editTaskButton" id="taskID">Edit Task</button>
</div>
</div>
</div>
</div>
Next, you would have jQuery clone the ProjectWrapperTemplate element, and set all of the corresponding fields.
$(function () {
$.ajax({
url: '/Project/GetTasks',
type: "POST",
data: { }
}).done(function (data) {
data.forEach(function (element) {
AppendProjectWrapper(element);
});
});
function AppendProjectWrapper(data) {
var projectAccordionWrapper = $('#ProjectAccordionWrapper');
var projectWrapper = $('#ProjectWrapperTemplate').clone(true, true);
projectWrapper.id = nothing; // remove the id, so as to not have duplicates
projectWrapper.style.display = nothing; // remove the style "display: none"
var itemName = projectWrapper.children('#itemName'); // h3
itemName.id = nothing;
itemName.text(data.ItemName);
var itemProjectID = projectWrapper.children('#itemProjectID'); // button Create New Task
itemProjectID.id = data.ItemProjectID;
var portletTemplate = projectWrapper.children('#portletTemplate'); // div
data.Tasks.forEach(function (element) {
var portlet = portletTemplate.clone();
portlet.id = nothing;
var taskName = portlet.children('#taskName');
taskName.id = nothing;
taskName.text(element.TaskName);
var taskDescription = portlet.children('#taskDescription');
taskDescription.id = nothing;
taskDescription.text(element.TaskDescription);
var editTaskButton = portlet.children('#taskID');
editTaskButton.id = element.TaskID;
portlet.appendTo(projectWrapper);
});
portletTemplate.remove(); // remove the portlet template element
projectWrapper.appendTo(projectAccordionWrapper);
}
}
Finally, have '/Project/SaveTask' return a JSON formatted TaskManagementApplication.Models.Project of the currently saved task.
$.ajax({
url: '/Project/SaveTask',
type: "POST",
data: { "taskName": taskName, "taskDescription": taskDescription, "taskID": id }
}).done(function (data) {
AppendProjectWrapper(data);
});
The return data for '/Project/GetTasks' should look as follows:
[
{
ItemName: '#item.Name',
ItemProjectID: '#item.ProjectID',
Tasks: [
TaskName: '#task.TaskName',
TaskDescription: '#task.TaskDescription',
TaskID: '#task.TaskID'
]
}
]
The return data from '/Project/SaveTask' should follow the same format, except or the outer-most array.
Please note that a lot of this code is untested.
It may be easiest to refactor the list into another action+view. Then, you can call this in both the original Index.cshtml view, and via the .load() method in jQuery. So, assuming this:
Projects controller
[HttpGet]
[ChildActionOnly]
public ActionResult Tasks(int id)
{
// create the appropriate model object as an IEnumerable of your Task type
return View(model);
}
Tasks.cshtml
#foreach(var task in Model) {
var buttonClass = "taskID" + task.TaskID;
<div class="portlet">
<div class="portlet-header">#task.TaskName</div>
<div class="portlet-content">#task.TaskDescription</div>
<button class="editTaskButton" id="#task.TaskID">Edit Task</button>
</div>
}
You would adjust Index.cshtml like so:
#model IEnumerable<TaskManagementApplication.Models.Project>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="ProjectAccordionWrapper">
#foreach (var item in Model)
{
<div class="ProjectWrapper">
<h3>#item.Name</h3>
<div class="column">
<button class="createTaskButton" id="#item.ProjectID">Create New Task</button>
<div id="tasks-#item.ProjectID">
#Html.Action("Tasks", "Project", new { id = item.ProjectID })
</div>
</div>
</div>
}
</div>
//... the rest of the view
And finally,
// this should happen inside the callback of your .ajax() method
$('#tasks-'+projectID).load('/project/tasks/'+ projectID);

Categories

Resources