I need to call Javascript alert function in c# method if web service is not available. I am using as.net core and webapi for webservice.
Here is the code
public List<EmployeeModel> GetEmployeeByEmpNo(string empNo)
{
try
{
string Baseurl = sys_ser.getApiURL();
EmployeeModel EmpInfo = new EmployeeModel();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync("api/Values/GetEmployeeByEmpNo/" + empNo).Result;
if (Res.IsSuccessStatusCode)
{
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
var empobjList = JsonConvert.DeserializeObject<List<EmployeeModel>>(EmpResponse);
//var EmpObj = empobjList[0];
if (empobjList != null)
{
return empobjList;
}
}
}
}
catch(Exception ex)
{
//<Srcript> alert('WebService is not available' + ex.message)</>
}
return null;
}
If AJAX isn't an option, you can pass a flag to tell the client to create the window:
Controller:
return View("Index", (object)errorDetails);
View:
#model string
<!--Your HTML-->
#if (!string.IsNullOrEmpty(Model)
{
<script type="text/javascript">
alert(Model);
</script>
}
Related
I am trying to get my modal to display details of announcement that has been created. I am using .net core. I have added my details method in my controller and added breakpoints to it and notice that i'm not even hitting my method. I'm new to software development and I'm not sure where I'm going wrong.
I have an announcement model and ViewModel which displays a list of Announcements -> public IEnumerable Announcements {get; set;}.
My button to trigger the modal:
// View Popup
$('.btn-view').click(function () {
var announcementId = $(this).attr("data-id");
console.log('announcementId:' + announcementId);
viewAnnouncement(announcementId);
});
JS to view details:
// Announcement Details
function viewAnnouncement(announcementId) {
try {
console.log('viewAnnouncement(' + announcementId + ')');
var url = applicationBaseUrl + '/Admin/Announcements/Details' + announcementId;
console.log('url: ' + url);
var label = 'Announcement Details';
var method = "GET";
var jsonPayload = null;
var showPostButton = false;
var postButtonFunction = null;
AjaxModal(url, label, jsonPayload, method, showPostButton, postButtonFunction);
}
catch (err) {
alert(err.message);
}
};
Method in my controller:
[HttpGet]
public async Task<IActionResult> Details(int? id)
{
try
{
if (id == null)
{
return NotFound();
}
Announcements announcement = _manager.Get((int)id);
if (announcement == null)
{
return NotFound();
}
return PartialView(announcement);
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
return View("Error", GetError(exc));
}
}
I followed the video and I can display a real-time value using SignalR in tag. But I don't know what signalr script code do so when I add a similar code to display 2 real-time values in 2 tags , it just displays one. I really hope someone will know clearly about that SignalR and please tell me something's wrong in my project? Thank you so much!
My code in index.html :
<script type="text/javascript">
$(function () {
//Proxy created on the fly
var cus = $.connection.cusHub;
//Declare a function on the job hub so the server can invoke
cus.client.displayValue = function () {
getData();
getData1();
};
//Start the connection
$.connection.hub.start();
getData();
getData1();
});
function getData() {
var $tbl = $('#tblValue');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
model.Value
);
});
}
});
}
function getData1() {
var $tbl = $('#tblValue1');
$.ajax({
url: $("#Get1").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus1, function (i1, model) {
$tbl.append
(
model.Value
);
});
}
});
}
</script>
Tag h2 with id="tblValue"> runs and has its value but not with id="tblValue1" :
<div class="col-md-6 col-lg-3">
<div class="statistic__item statistic__item--orange">
<h2 id="tblValue" class="number">
</h2>
<span class="desc">MONTHLY COST</span>
<div class="icon">
<i class="zmdi zmdi-money"></i>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="statistic__item statistic__item--blue">
<h2 id="tblValue1" class="number">1,086</h2>
<span class="desc">YEARLY USAGE</span>
<div class="icon">
<i class="zmdi zmdi-time"></i>
</div>
</div>
</div>
My code in Controller ( I just copy paste from function JsonResult Get ) :
public JsonResult Get()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ValueConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand value1 = new SqlCommand(#"SELECT [DeviceID],[Value] FROM [dbo].[Device1] WHERE [DeviceID]='PM1'", connection))
{
value1.Notification = null;
SqlDependency dependency = new SqlDependency(value1);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = value1.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
DeviceID = (string)x["DeviceID"],
Value = (double)x["Value"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
public JsonResult Get1()
{
using (var connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ValueConnection"].ConnectionString))
{
connection1.Open();
using (SqlCommand value1 = new SqlCommand(#"SELECT [DeviceID],[Value] FROM [dbo].[Device1] WHERE [DeviceID]='PM2'", connection1))
{
value1.Notification = null;
SqlDependency dependency1 = new SqlDependency(value1);
dependency1.OnChange += new OnChangeEventHandler(dependency_OnChange1);
if (connection1.State == ConnectionState.Closed)
connection1.Open();
SqlDataReader reader1 = value1.ExecuteReader();
var listCus1 = reader1.Cast<IDataRecord>()
.Select(x => new
{
DeviceID = (string)x["DeviceID"],
Value = (double)x["Value"],
}).ToList();
return Json(new { listCus1 = listCus1 }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
private void dependency_OnChange1(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
My code in CusHub.cs :
public class CusHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CusHub>();
context.Clients.All.displayValue();
}
}
I am fairly new to Ajax. I m trying to call ajax on Logout link, before logout function perform i want to validate any progress running ,
if Spring controller response String value "True" than Link work and if response in string false than Link not work and show alert or Message.
function callLogout() {
var A;
if(window.XMLHttpRequest)
{
A=new XMLHttpRequest();
}
A.onreadystatechange=function()
{
if(A.readyState==4)
{
var data = A.responseText.split('##');
if (data[1].trim() != null && data[1].trim() != '')
showNotification('bg-red', data[1].trim(), 'top', 'center', '', ''); // its work like alert using jquery
}
}
A.open('GET','/PMS-1.0.0.3/logout1',true);
A.send();
}
My Controller
#RequestMapping(path = "/logout1" , method=RequestMethod.GET)
public ModelAndView logout1(HttpSession session ,EmployeeModel employeeModel, HttpServletRequest req) {
ModelMap map = new ModelMap();
EmployeeMaster master = null;
System.out.println("in logout1 Method");
long emp_id = (long) session.getAttribute("userid");
ActivityTaskDetails activityTaskDetails = activityTaskRepository.getActiveTaskDetails(emp_id);
System.out.println("Value get From activity task"+activityTaskDetails);
if(activityTaskDetails != null){
map.addAttribute("LogoutValidate","Work in Progress, Youy cant Logout.");
return new ModelAndView("ajaxpage", map);
}
else{
System.out.println("Else Part session invalidate");
session.removeAttribute("username");
session.removeAttribute("userid");
for (int i=0; i<Global.employeeRightsList.size(); i++) {
session.removeAttribute("employeeRights_"+Global.employeeRightsList.get(i).getFormMaster().getFormName());
}
return new ModelAndView("redirect:/login");
}
}
Ajax Page
<c:if test="${LogoutValidate != null}">
##${LogoutValidate}
</c:if>
I am running the following script on the client-side and the script is failing to update, when there is change in the database. I debugged the script using DevTools and discovered my Jquery scripts are responding back as "304 not modified". Does this issue, indicate why the client-side content is failing to update.
<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery-1.6.4.min.js"></script>
<script src="../Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.NotificationHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function (role, descrip) {
// Add the message to the page.
$('#spanNewMessages').text(role);
$('#spanNewCircles').text(descrip);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications();
alert("Notifications have been sent.");
}).fail(function (e) {
alert(e);
});
//$.connection.hub.start();
});
</script>
<h1>New Notifications</h1>
<div>
<br />
<b>New <span id="spanNewMessages"></span> = role.</b><br />
<b>New <span id="spanNewCircles"></span> = descrip.</b><br />
</div>
Hub Class:
[HubName("NotificationHub")]
public class notificationHub : Hub
{
string role = "";
string descrip = "";
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ConnectionString))
{
string query = "SELECT top 1 [role],[description] FROM [dbo].[User] order by uploadDate desc";
connection.Open();
SqlDependency.Start(GetConnectionString());
using (SqlCommand command = new SqlCommand(query, connection))
{
try
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
role = dt.Rows[0]["role"].ToString();
descrip = dt.Rows[0]["description"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
Clients.All.RecieveNotification(role, descrip);
}
[HubMethodName("onStatusChanged")]
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Insert)
{
notificationHub nHub = new notificationHub();
nHub.SendNotifications();
}
}
Please advice. Thank you.
In Microsoft Visual Studio Express I have started a new project using the "Windows Phone HTML5 App" template. If I run the emulator, everything works fine. Next I added the following JavaScript to the index.html page:
<script type="text/javascript">
window.onload = function(){
alert(window.location.href); // --> x-wmapp0:/Html/index.html
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
alert('ON READY STATE CHANGE');
if(xmlhttp.readyState==4){
alert(xmlhttp.responseText);
}
}
//xmlhttp.open("GET","text.txt",true); // I have tried all of these
//xmlhttp.open("GET","Html/text.txt",true);
//xmlhttp.open("GET","/Html/text.txt",true);
xmlhttp.open("GET","x-wmapp0:/Html/text.txt",true);
xmlhttp.send();
}
</script>
Now when I run the app in the emulator I get the first alert with the window location, but do not get any alerts from the readyState or onreadystatechange. The text.txt file is on the same level as the index.html. I have run this code in IE10 and it works just fine. Any ideas on what I am doing wrong?
Update: I have deployed this on an actual Windows 8 phone and got the same result
Cheers
Here is what Microsoft told me from MSDN
XMLHttpRequest only works for retrieving network resources. i.e. You cannot use it to access content from your applications local storage, i.e. XAP or IsolatedStorage.
Here is an example of script + code which I have used in the past to work around this limitation:
HTML Page with JavaScript:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script type="text/javascript">
function LoadFile(SourceURL) {
try {
var httpfreq = new XMLHttpRequest();
httpfreq.onreadystatechange = function () {
filecontent.innerText = "httpfreq.onreadystatechange fired, readyState = " + httpfreq.readyState.toString();
if (httpfreq.readyState = 4) {
filecontent.innerText = "Status = " + httpfreq.status.toString();
if (httpfreq.status = 200) {
window.external.notify("Received content" + httpfreq.responseText);
filecontent.innerHTML = httpfreq.responseText;
}
else {
window.external.notify("Error loading page: " + SourceURL);
filecontent.innerText = "Error loading page " + SourceURL;
}
}
};
httpfreq.open("GET", SourceURL);
httpfreq.send(null);
}
catch (e) {
if (e.number = 0x80070005) {
LoadLocalFile(SourceURL, "GetResourceCallback");
}
else {
alert(e.name + " " + e.number.toString());
}
}
}
function LoadLocalFile(SourceURL, callbackfn) {
window.external.notify("GetResource?file=" + SourceURL + ";callback=" + callbackfn);
}
function GetResourceCallback(StringContent) {
filecontent.innerText = StringContent;
}
</script>
</head>
<body>
<p>
test page: notes.html
</p>
<p><input type="button" onclick="LoadFile('text.txt')" value="Load Local" /> </p>
<p><input type="button" onclick="LoadFile('http://www.somedomain.com/text.txt')" value="Load remote" /> </p>
<p>---------------------------</p>
<div id="filecontent"></div>
<p>---------------------------</p>
</body>
</html>
And the required App Host code (c#)
private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Script Notify : {0}",e.Value);
if (e.Value.Contains("GetResource?file="))
{
Dispatcher.BeginInvoke(() =>
{
String szArgs = e.Value;
string szResource = null;
string szCallbackFn = null;
char[] separators = new char[2] {'?',';'};
string[] parms = szArgs.Split(separators);
for (int i = 1; i < parms.Length; i++ )
{
if (parms[i].Contains("file="))
{
szResource = parms[i].Substring(5);
}
else if (parms[i].Contains("callback="))
{
szCallbackFn = parms[i].Substring(9);
}
}
if (!String.IsNullOrWhiteSpace(szResource) && !String.IsNullOrWhiteSpace(szCallbackFn))
{
// read local resource.
string szFileContent= "Resource not found!";
try
{
if (String.IsNullOrEmpty(webBrowser1.Base))
{
// if Base is not set then assume XAP file content.
szFileContent = ReadXAPResource(szResource);
}
else
{
// else assume IsolatedStorage
szFileContent = ReadISOFile(webBrowser1.Base, szResource);
}
}
catch (Exception)
{}
webBrowser1.InvokeScript(szCallbackFn, szFileContent);
}
});
}
}
private string ReadXAPResource(string szFile)
{
string szContent = "File Not Found";
try
{
// in my project HTML files are in the HelpContent folder...
StringBuilder szPath = new StringBuilder("HelpContent");
if (!szFile.StartsWith("/"))
szPath.Append("/");
szPath.Append(szFile);
StreamResourceInfo sri = Application.GetResourceStream(new Uri(szPath.ToString(), UriKind.Relative));
if (null != sri)
{
StreamReader strm = new StreamReader(sri.Stream);
szContent = strm.ReadToEnd();
}
}
catch (Exception) { }
return szContent;
}
private string ReadISOFile(string szBase, string szFile)
{
string szContent = "File Not Found";
try
{
string fullPath = szBase + szFile;
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfsInput = isf.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (null != isfsInput)
{
StreamReader strm = new StreamReader(isfsInput);
szContent = strm.ReadToEnd();
}
}
catch (Exception) { }
return szContent;
}