Pass parameters to Common.js from Aspx in .Net - javascript

I have a web application with Common.js and it has the following function which is calling when this button btnBookingStatus was clicked.
$(document).on('click', '#btnBookingStatus', function () {
var req = new Object();
req.strMinNo = $(parent.document).find('#hdnFMinNo').val();
req.strSeqNo = $(parent.document).find("#hdnPSeqNo").val();
req.strUserId = $(parent.document).find("#hdnUserId").val();
if (req.strMinNo == undefined || req.strMinNo == '') {
req.strMinNo = $(parent.document).find('#hdnMinNo').val();
}
if (req.strSeqNo == undefined || req.strSeqNo == '') {
req.strSeqNo = $(parent.document).find('#hdnFinSeqNo').val();
}
if (req.strUserId == undefined || req.strUserId == '') {
req.strUserId = $(parent.document).find('#hdnCurrentUserId').val();
}
$.ajax({
type: "POST",
data: JSON.stringify(req),
url: "../Common/LibUiUtilities.aspx/fnCreamsBookingStatus",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null) {
var retData = JSON.parse(data.d);
if (retData.oRetunStatus == 'P' || retData.oRetunStatus == 'null') {
alert("Creams Booking still in progress...");
}
else {
$(parent.document).find('#drpBookingStatus').removeAttr('disabled');
$(parent.document).find('#drpBookingStatus').val(retData.oRetunStatus);
$(parent.document).find('#drpBookingStatus').attr('readonly', true);
alert("Creams Booking Success");
}
if (retData.oReturnMsg != undefined && retData.oReturnMsg != 'null') {
$(parent.document).find('#lblBkWarningMsg').text(retData.oReturnMsg);
} else {
$(parent.document).find('#lblBkWarningMsg').empty();
}
}
}
});
});
There are 5 client windows with the same btnBookingStatus button with the same functionality, which needs to be called the above-mentioned JS function. But the hidden field names which pass the parameters are different.
For eg:-
Form1.aspx --> hdnFMinNo, hdnFSeqNo
Form2.aspx --> hdnPMinNo, hdnPSeqNo
Form3.aspx --> hdnMinNo, hdnSeqNo
These element Ids can not be changed
I wanted to pass the parameters (MIN_NO and SEQ_NO) from ASPX to the Common.js without accessing the parent window's elements.
Please help me out with this.

Related

How to call a modal window on browser close or back button in asp.net?

I have a back button on my page. on click of that back button following code executes.
PageInformation InfoView = new PageInformation ();
InfoView = (PageInformation )ViewState["PBLSave"];
if (txtValidFPGTE18MQ1.Text != InfoView.FPGTE18.Q1.ToString() || txtValidFPGTE18MQ2.Text != InfoView.FPGTE18.Q2.ToString()
|| txtValidFPGTE18MQ3.Text != InfoView.FPGTE18.Q3.ToString() || txtValidFPGTE18MQ4.Text != InfoView.FPGTE18.Q4.ToString()
|| txtValidFPGTE18MQ5.Text != InfoView.FPGTE18.Q5.ToString() || txtValidFPGTE18MQ6.Text != InfoView.FPGTE18.Q6.ToString())
{
mdlPopupExtender.Show();
}
else
{
redirectUrl = "../UI/Summary_Page.aspx";
Response.Redirect(redirectUrl);
}
here the mdlPopupExtender is my custom made modal Window. I want to execute this entire code and show this modal window on click of Browser close[X] and Browser back button. How do I do this?
Assuming that the function name is RunOnClose
In CS File
[System.Web.Services.WebMethod()]
public static void RunOnClose()
{
PageInformation InfoView = new PageInformation ();
InfoView = (PageInformation )ViewState["PBLSave"];
if (txtValidFPGTE18MQ1.Text != InfoView.FPGTE18.Q1.ToString() || txtValidFPGTE18MQ2.Text != InfoView.FPGTE18.Q2.ToString()
|| txtValidFPGTE18MQ3.Text != InfoView.FPGTE18.Q3.ToString() || txtValidFPGTE18MQ4.Text != InfoView.FPGTE18.Q4.ToString()
|| txtValidFPGTE18MQ5.Text != InfoView.FPGTE18.Q5.ToString() || txtValidFPGTE18MQ6.Text != InfoView.FPGTE18.Q6.ToString())
{
mdlPopupExtender.Show();
}
else
{
redirectUrl = "../UI/Summary_Page.aspx";
Response.Redirect(redirectUrl);
}
}
In aspx file
<script type="text/javascript">
window.onbeforeunload = function () {
$.ajax({
type: "POST",
url: "WebForm1.aspx/RunOnClose",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert('Funtion called!');
},
error: function () {
alert('Funtion not called');
}
});
};
</script>

How to catch session timeout in ajax call?

Please note that I had already tried to apply the solution on Handling session timeout in ajax calls but did not worked for me.
In an ASP.NET MVC5 project, I open pages by rendering partialview via AJAX as shown below:
function renderPartial(e, controller, action) {
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
var message = errorThrown;
if (jqXHR.responseJSON != null) {
message = jqXHR.responseJSON.message;
}
},
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
//Load partialview
$("#div-page-content").html(data);
}
});
};
On the other hand, when session timeout and call this method by a hyperlink, there is an empty white page on the partialview field where partialview page should be rendered. So, is it possible:
1) to display a partialview at this field?
2) to redirect user Login page?
Note: I would also be happy if you suggest a smart way to Handle Session Expire in ASP.NET MVC. Thanks in advance...

How to open file using Ajax in MVC

I have an hyperlink of the file name and want to download the file retrieved from database. I can download the file, but the form is posted during this process. Instead of this, I want the form is not posted with the help of ajax, but my code hits error in Ajax call. Is there a smart way to achieve this?
View:
<a onclick="downloadFile(#Model.ID);" target="blank">#Model.FileName</a>
<script>
function downloadFile(id) {
$.ajax({
url: '#Url.Action("Download", "Controller")',
type: "POST",
data: JSON.stringify({ 'id': id }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("error occurs on the database level!");
}
},
error : function () {
alert("an error has occured!!!");
}
});
}
</script>
Controller:
public FileContentResult Download(int id)
{
var dataContext = repository.Attachments.FirstOrDefault(p => p.ID == id);
if (dataContext != null)
{
return File(dataContext.FileData, dataContext.FileMimeType);
}
else
{
return null;
}
}
why not just change your link to
<a href="#Url.Action("Download", "Controller", new { id = Model.ID })" >#Model.FileName</a>
The easiest way to download a file is to link it directly like calling the action: "/FileController/Download?Id=2"
The problem is that if you get an error, it will redirect you to a blank page...
To resolve this i created this function:
function DownloadFile(id, Type) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
if (Type == undefined || Type == "")
Type = null;
iframe.src = "/File/Download?ID=" + id;
}
This function creates an hidden iframe pointing to the file path (action). If it gives an error, it will not blow up your page.

Link to page after ajax scripts have run (javascript anchor?)

I have a MVC web app that receives data from a database and displays it in a table for the user. The user goes through a series of dropdowns and buttons, each being populated using AJAX calls. Then a table is created and shown. As an example, here is one such section of code.
#Html.LabelFor(model => model.RootID)
#Html.DropDownListFor(model => model.RootID, Model.AvailableRoots)
<input type="button" id="RootsBtn" value="Go" />
<script language="javascript" type="text/javascript">
$(function () {
$("#RootsBtn").click(function () {
var selectedItem = $('#RootID').val();
$("#MiscTable").empty();
$.ajax({
cache: false,
type: "GET",
url: RootDirectory + "Home/GetTableData/",
data: { "id": selectedItem },
success: function (data) {
var myTable = $('#MiscTable');
$.ajax({
cache: false,
type: "GET",
url: RootDirectory + "Home/GetProperties/",
data: { "id": selectedItem },
success: function (data2) {
if (data2['IsAddAvailable'] == 'True' && data2['IsViewOnly'] == 'False' && data2['IsEnabled'] == 'True' &&
data2['IsViewOnly_User'] == 'False' && data2['IsEnabled_User'] == 'True') {
$('#Add' + data2['TableName']).show();
}
if (data.length > 0) {
var firstRecord = data[0];
var headerRow = $('<thead>');
for (var columnTitle in firstRecord) {
headerRow.append($('<th>', { text: columnTitle }));
}
headerRow.append($('<th>', { text: " " }));
myTable.append(headerRow);
var record;
var dataRow;
for (var dataIndex = 0; dataIndex < data.length; dataIndex++) {
record = data[dataIndex];
dataRow = $('<tr>');
for (var column in firstRecord) {
dataRow.append($('<td>', { text: record[column] }));
}
var id = record['ID'];
var showDelete = ((record['IsDeleteAvailable'] == 'True' || ((record['IsDeleteAvailable'] == null || record['IsDeleteAvailable'] == "") && data2['IsDeleteAvailable'] == 'True')) && data2['IsDeleteAvailable_User'] == 'True');
var showEdit = ((record['IsEditAvailable'] == 'True' || ((record['IsEditAvailable'] == null || record['IsEditAvailable'] == "") && data2['IsEditAvailable'] == 'True')) && data2['IsEditAvailable_User'] == 'True');
var str1 = RootDirectory + data2['TableName'] + "/Edit/" + id;
var str2 = RootDirectory + data2['TableName'] + "/Details/" + id;
var str3 = RootDirectory + data2['TableName'] + "/Delete/" + id;
if (showDelete && showEdit && data2['IsViewOnly'] != 'True' && data2['IsViewOnly_User'] != 'True') {
dataRow.append('<td>Edit<br />Details<br />Delete</td>');
}
else if (!showDelete && showEdit && data2['IsViewOnly'] != 'True' && data2['IsViewOnly_User'] != 'True') {
dataRow.append('<td>Edit<br />Details</td>');
}
else if (showDelete && !showEdit && data2['IsViewOnly'] != 'True' && data2['IsViewOnly_User'] != 'True') {
dataRow.append('<td>Details<br />Delete</td>');
}
else {
dataRow.append('<td>Details</td>');
}
myTable.append(dataRow);
}
}
},
error: function (xhr, ajaxOptions, throwError) {
alert("Error");
}
});
$('#MiscTable').show();
},
error: function (xhr, ajaxOptions, throwError) {
alert("Error");
$('#MiscTable').hide();
}
});
});
});
</script>
Everything works right now to display whatever table has been chosen by the user in the dropdown list. When the user uses a link in the table (Edit, Details, Delete) they are taken to a new page to handle this action. When finished it takes them back to this main page. Unfortunately the state of their dropdowns and table were obviously not stored, so they have to go through the menus again to see their changes.
I have heard that there are anchors that can allow a page to go to a specific configuration of javascript/AJAX. I've tried to search for it but haven't been successful. What I am wanting is the ability for the user to search through my dropdowns and select table X. Then in table X they can say to edit item Y. When finished editing Y and clicking submit (or back to table to undo changes) rather than going back to the start of the main page, it should repopulate the dropdowns and go back to showing table X.
Maybe a link like /Home/Index/#X?
Is this possible and how would it be done?
You're talking about hash fragments. In a general sense, all this is doing is using the target as a dumping ground for data needed to render the page as it was, since the target portion of the URL is not sent to the server and doesn't cause a page refresh. On it's own this does nothing, but you could have JavaScript on page that parses this information out of the URL and does something meaningful with it.
So for your purposes you could go with something like:
`/path/to/page#select1=foo&select2=bar`
Then, you would need JS on that page that pulls out the fragment (location.hash) and parses out the name value pairs to finally use that to set the selects back to the state they were in previously and load whatever data needs to be loaded via AJAX.

JavaScript Validation error?

I have been working on a JavaScript validator, but for some reason, evalid always returns as false even if it has passed validation... this is a bug as if evalid is false, the form doesn't submit.
function signup_validate()
{
document.getElementById("email_error").innerHTML = "";
document.getElementById("password_error").innerHTML = "";
evalid = false;
pvalid = false;
email = null;
pass = null;
confpass = null;
email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
atpos=email.indexOf("#");
dotpos=email.lastIndexOf(".");
pass=document.forms["signup_form"]["pass"].value;
confpass=document.forms["signup_form"]["confpass"].value;
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
}
else
{
$.post('/resources/forms/signup.php',{email: email}, function(data){
if(data.exists){
document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
}
else
{
evalid = true;
}
}, 'JSON');
}
if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
{
pvalid = true;
}
else
{
document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
}
alert(evalid);
if (evalid == true && pvalid == true)
{
document.getElementById("signup_form").submit();
}
else
{
return false;
}
}
What could I have missed?
The only moment when you set "evalid" true is inside a function that runs asynchronously. In other words, by the time you set "evalid" true the main function has already reached the end.
You Could try to use $.ajax instead of $.post and use the parameter async:false
Try something like this:
$.ajax({
type: 'POST',
url: '/resources/forms/signup.php',
data: {email: email},
success: function(response){
//your function here
},
dataType:'JSON',
async:false
});

Categories