I have a login page and want to show an alert when the user login was successful. but when I use JavaScript it doesn't work. in fact everything works just this javaScript doesn't work.
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(tblUser user)
{
if (ModelState.IsValid)
{
var logData = UserBLL.LogInCheck(user);
if (logData != null)
{
JavaScript("alert(Wellcome Dear Admin)");
Session["user"] = "Admin";
return RedirectToAction("Index", "Home");
}
}
return View();
}
I don't know what to do!!!
You can redirect the user by the javascript. So only return the Javascriptresult.
see the code below :-
[HttpPost]
public ActionResult LogIn(tblUser user)
{
if (ModelState.IsValid)
{
var logData = UserBLL.LogInCheck(user);
if (logData != null)
{
Session["user"] = "Admin";
return JavaScript("alert(Wellcome Dear Admin); window.location.href = '" + Url.Action("Index", "Home") + "';");
}
}
return View();
}
Try this:
[HttpPost]
public ActionResult LogIn(tblUser user)
{
if (ModelState.IsValid)
{
var logData = UserBLL.LogInCheck(user);
if (logData != null)
{
Session["user"] = "Admin";
TempData["LoginSuccess"] = "1";
}
}
return View();
}
In cshtml:
#if (TempData["LoginSuccess"] != null)
{
<script type="text/javascript">
alert("Welcome Dear Admin!");
window.location.href = '#Url.Action("Index", "Home")';
</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'm working on an online attendance portal, In which I've set a condition in a controller that users can't mark attendance twice a day. They are only allowed to mark attendance once per day. So I want to show a message on the view page "Create" that "Attendance is already marked" if an employee is marking the attendance a second time on the same date. I've set an alert message but I want to show a message on the view page from where the employee is marking the attendance. I've searched for it a lot but can't find any better one.
Here's my Controller Code
[Authorize]
public ActionResult Create()
{
Employee employee = JsonConvert.DeserializeObject<Employee>(User.Identity.Name);
return View(new Attendance() { Emp_Id = employee.Emp_Id });
}
[HttpPost]
public ActionResult Create(Attendance attendance)
{
if (ModelState.IsValid)
{
try
{
var attdate = attendance.Date;
var nextdate = attdate.AddDays(1);
var id = Convert.ToInt32(Session["UserID"]);
var isExist = db.Attendance.FirstOrDefault(i => i.Emp_Id == id && i.Date == attdate && i.Date < nextdate);
if (isExist != null)
{
//Here i set the alert but i want to show message on view page.
return Content("<script language='javascript' type='text/javascript'>alert('Your Attendance is Already Marked');</script>");
}
else
{
//var res = tempDate.Date;
db.Attendance.Add(attendance);
db.SaveChanges();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
}
}
return RedirectToAction("Index", "Attendance");
}
Controller:
if (isExist != null)
{
TempData["Msg"] = "Your Attendance is Already Marked'"
}
View:
<body>
#if (TempData["Msg"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert(#TempData["Msg"]);
};
</script>
}
</body>
To display my message, I do this:
Model:
public class Alert
{
public const string TempDataKey = "TempDataAlerts";
public string AlertStyle { get; set; }
public string Message { get; set; }
public bool Dismissible { get; set; }
}
public class AlertStyle
{
public const string Success = "success";
public const string Information = "info";
public const string Warning = "warning";
public const string Danger = "danger";
}
My BaseController:
public class BaseController: Controller
{
public void Success(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Success, message, dismissible);
}
public void Information(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Information, message, dismissible);
}
public void Warning(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Warning, message, dismissible);
}
public void Danger(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Danger, message, dismissible);
}
private void AddAlert(string alertStyle, string message, bool dismissible)
{
var alerts = TempData.ContainsKey(Alert.TempDataKey)
? (List<Alert>)TempData[Alert.TempDataKey]
: new List<Alert>();
alerts.Add(new Alert
{
AlertStyle = alertStyle,
Message = message,
Dismissible = dismissible
});
TempData[Alert.TempDataKey] = alerts;
}
}
And in any controller I need is enough:
public class PanelController : BaseController
{
public ActionResult Index()
{
Success($"Hello World!!!",true);
return View();
}
}
PartialView for alert or message
#{
var alerts = TempData.ContainsKey(Alert.TempDataKey)
? (List<Alert>)TempData[Alert.TempDataKey]
: new List<Alert>();
#*if (alerts.Any())
{
<hr />
}*#
foreach (var alert in alerts)
{
var dismissibleClass = alert.Dismissible ? "alert-dismissible" : null;
<div class="alert alert-#alert.AlertStyle #dismissibleClass">
#if (alert.Dismissible)
{
<button type="button" class="close pull-left" data-dismiss="alert" aria-hidden="true">×</button>
}
#Html.Raw(alert.Message)
</div>
}
}
Finally:
<div class="mt-alerts">
#{ Html.RenderPartial("_Alerts"); }
</div>
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>
}
I have do a sse demo,but it not work, i post the js and java code,please tell me what's the wrong,thank you.
this is the js:
if (window.EventSource) {
var source = new EventSource('http://127.0.0.1:8080/pushweb/push');
source.addEventListener('message', function(e) {
console.log(e.data, this.readyState);
},false);
source.addEventListener('open', function(e) {
console.log("conncted",this.readyState);
},false);
source.addEventListener('error', function(e) {
if (e.target.readyState == EventSource.CLOSED) {
console.log("closed");
} else if(e.target.readyState == EventSource.CONNECTING){
console.log("connecting");
}else {
console.log("error"+this.readyState);
}
}, false);
} else {
console.log("not support SSE");
}
this is the springmvc code:
#CrossOrigin(origins = "*", maxAge = 3600)
#Controller
public class PushController
{
#RequestMapping(value = "/push", produces = "text/event-stream;charset=UTF-8")
#ResponseBody
public String push()
{
String str =Long.toString(System.currentTimeMillis());
return "data:"+str + "\n\n\n";
}
#RequestMapping(value = "/message")
#ResponseBody
public String message()
{
String stre = "hello";
return stre;
}
}
this is the chrome console result
On the server side, you need to use SseEmitter to send events. See Server-Sent Events with Spring (blog).
I am trying to create a demo of Group Chat using reverse ajax in Spring. I am using Spring 3.2.0.RELEASE version.
I am using DeferredResult to perform reverse ajax in my controller. Following is the snippet of my Controller class.
#Autowired
private AsyncRepository asyncRepository;
Map<Integer, List<DeferredResult<String>>> watchers = new ConcurrentHashMap<Integer, List<DeferredResult<String>>>();
#RequestMapping(value="/asyncRequest/getMessages/{id}", method=RequestMethod.GET)
#ResponseBody
public DeferredResult<String> getMessages(final #PathVariable("id") Integer id){
final DeferredResult<String> deferredResult = new DeferredResult<String>(null, Collections.emptyList());
if(watchers.containsKey(id)) {
watchers.get(id).add(deferredResult);
} else {
watchers.put(id, new ArrayList<DeferredResult<String>>());
watchers.get(id).add(deferredResult);
}
deferredResult.onCompletion(new Runnable() {
#Override
public void run() {
watchers.get(id).remove(deferredResult);
}
});
return deferredResult;
}
#RequestMapping(value="/asyncRequest/setMessages/{id}/{message}", method=RequestMethod.GET)
#ResponseBody
public String setMessage(#PathVariable("id") Integer id, #PathVariable("message") String message) {
asyncRepository.setMessage(id, message);
return "";
}
#Scheduled(fixedRate=1000)
public void processQueues() {
for (Map.Entry<Integer, Queue<AsyncDataBean>> entry : asyncRepository.getAsyncBeans().entrySet()) {
while(entry != null && entry.getValue() != null && !entry.getValue().isEmpty()) {
AsyncDataBean asyncDataBean = entry.getValue().poll();
for (DeferredResult<String> deferredResult : watchers.get(asyncDataBean.getId())) {
deferredResult.setResult(asyncDataBean.getMessage());
}
}
}
}
And below is the Repository class which holds the Map of GroupID and its relevant messageQueue. And it also has the functions for getting and setting the messages for relevant group id.
#Repository
public class AsyncRepository {
private Map<Integer, Queue<AsyncDataBean>> asyncBeans = new ConcurrentHashMap<Integer, Queue<AsyncDataBean>>();
public String getMessages(Integer id) {
StringBuilder stringBuilder = new StringBuilder();
while (asyncBeans.get(id) != null && !asyncBeans.get(id).isEmpty()) {
stringBuilder.append(asyncBeans.get(id).poll().getMessage()).append("~");
}
return stringBuilder.toString();
}
public void setMessage(Integer id, String message) {
if(asyncBeans.containsKey(id)) {
asyncBeans.get(id).add(new AsyncDataBean(id, message));
} else {
Queue<AsyncDataBean> messageQueue = new ConcurrentLinkedQueue<AsyncDataBean>();
messageQueue.add(new AsyncDataBean(id, message));
asyncBeans.put(id, messageQueue);
}
}
public Map<Integer, Queue<AsyncDataBean>> getAsyncBeans() {
return asyncBeans;
}
public void setAsyncBeans(Map<Integer, Queue<AsyncDataBean>> asyncBeans) {
this.asyncBeans = asyncBeans;
}
}
And below is the data bean I am using to store each message with its group id.
public class AsyncDataBean {
private Integer id;
private String message;
public AsyncDataBean() {
}
public AsyncDataBean(int id, String message) {
this.setId(id);
this.setMessage(message);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And then comes the jsp page for group chat. which looks like below.
<script type="text/javascript">
var messagesWaiting = false;
function getMessages(){
if(!messagesWaiting){
$.ajax({ url: "${pageContext.servletContext.contextPath}/asyncRequest/getMessages/${id}",
dataType:"text",
success: function(data,textStatus,jqXHR) {
if(textStatus == 'success'){
messagesWaiting = false;
var arr = data.split("~");
for(var i=0; i<arr.length; i++)
{
try
{
if(arr[i] != '') {
$("#txtaMessages").val($("#txtaMessages").val() + "\n\n" + arr[i]);
document.getElementById("txtaMessages").scrollTop = document.getElementById("txtaMessages").scrollHeight;
}
}
catch(e){
alert(e.message);
}
}
}
},
complete: function(j) {
},
error: function(xhr) {
}
});
messagesWaiting = true;
}
}
setInterval(getMessages, 1000);
getMessages();
function sendMessage() {
var xmlhttp1 = new XMLHttpRequest();
xmlhttp1.open("GET", '${pageContext.servletContext.contextPath}/asyncRequest/setMessages/${id}/' + $("#txtMessage").val(), true);
xmlhttp1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp1.send();
$("#txtMessage").val("");
$("#txtMessage").focus();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<table>
<tr>
<td>Messages :: </td>
<td>
<textarea cols="100" rows="10" id="txtaMessages"></textarea>
</td>
</tr>
<tr>
<td>Send Message :: </td>
<td><input type="text" id="txtMessage"/></td>
</tr>
<tr>
<td><input type="button" value="Send" onclick="sendMessage();"/></td>
</tr>
</table>
</body>
</html>
That is what I have coded till now to get this working. And everything is working finw in FF and Chrome. But in IE it is not working as expected. The request is never gets hold on the server and it always gets executed every second as configured in the javascript code. And it always returns the same result as previous. I have tried to use several other methods to send ajax request for IE but its not working. Can anyone get it working for me?
Since everything works fine in FF and Chrome, I suspect the problem is with javascript code to send the request to get messages.
Please help me.
Thanks in advance.
This is very very frustrating.
To get this thing work properly in IE I need to set cache:false attribute in the ajax request I am creating with jquery for getMessages. Otherwise IE will not hold the request in pending status and always returns back with the old response text.
Its a very big issue with IE. I hope no one face the problem again or finds this answer as early as possible.
:)