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));
}
}
Related
I am working on a web application with ASP.NET core and I have encountered some issues.
I'm redirecting my application when I get to a controller, to another controller that opens a page. However, when I get to the controller that returns the view that should be opened, nothing happens and the page doesn't load. The request arrives at the controller which returns the view but the page does not open. The curious thing is that when creating a menu option for the page, everything works normally and the page is loaded.
The first controller is called by Ajax code, receives the information and then calls the other controller to open the other view. Could Ajax code be causing this problem?
Ajax Code
<script>
var listaDeIds = [];
function Mostrar() {
var videos = document.querySelectorAll('#video');
var count = 0;
var lista = [];
for (var i = 0; i < videos.length; i++) {
var videoID = videos.item(i).getAttribute("name");
const shadow = videos.item(i).shadowRoot;
const childNodes = Array.from(shadow.childNodes);
childNodes.forEach(childNode => {
if (childNode.nodeName === "DIV") {
const shadowChilds = Array.from(childNode.childNodes);
shadowChilds.forEach(shadowShild => {
if (shadowShild.nodeName === "DIV") {
const shadowChildsInternas = Array.from(shadowShild.childNodes);
shadowChildsInternas.forEach(interna => {
if (interna.nodeName === "INPUT") {
if (interna.checked === true) {
lista[count] = videoID;
count = count + 1;
}
}
});
}
});
}
});
}
if (lista.length > 0) {
document.getElementById("btnplaylist").style.display = 'block';
} else {
document.getElementById("btnplaylist").style.display = 'none';
}
listaDeIds = lista;
}
$('#Playlist').click(function () {
//var url = "/Playlist/RecebeListaDeIds";
var url = "/VideoSearch/PegarListaDeIds"
var lista = listaDeIds;
$.post(url, { pListaDeIds: lista }, function (data) {
$("#msg").html(data);
});
});
</script>
Controller 1 that receives data from the screen and calls the other controller
[HttpPost]
public ActionResult PegarListaDeIds(string[] pListaDeIds)
{
if(AppUser.User != null)
{
var appCache = AppCache.Instance;
appCache.VideoId.InserirNoCache(pListaDeIds);
return RedirectToAction("CreatePlaylist", "Playlist");
}
else
{
return BadRequest("Usuário não está logado");
}
}
Controller 2 which is called by controller 1. This controller when called by another controller does not load the View.
[HttpGet]
public ActionResult CreatePlaylist()
{
return View();
}
Problem solved. I added this snippet to my Ajax code and now everything works fine.
var url = '#Url.Action("CreatePlaylist", "Playlist")';
window.location.href = url.replace();
I have a dropdown list of cities and a button to add city into vendor model. So I want to add selected city name inside div when button clicked each time. For example, I have list of cities in dropdown and suppose I selected Bangalore and when clicked on add button then it should get added inside div and when I refresh the page, div list should be persistence. Which means, when page get reload or refreshed then added city should be displayed inside a div. Currently what I am suffering from is when I reload page then the cities I added after button clicked, gets emptied each time. So I want help regarding this. Any suggestions would be helpful for me.
Below is my api controller code to save selected city into database:
#RequestMapping(value = AkApiUrl.setdeliverycity, method = { RequestMethod.POST, RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> setdeliverycity(HttpServletRequest request, HttpSession session, #RequestParam("delivercityid") String delivercityid,
#RequestParam("vendorid") String vendorid) {
CustomResponse = ResponseFactory.getResponse(request);
try {
User loginuser = (User) session.getAttribute("user");
Long vid = Long.parseLong(vendorid);
User vendor = userDao.findByUserid(vid);
String vendorname = vendor.getName();
Long cid = Long.parseLong(delivercityid);
DeliveryCity city = deliverycityDao.findByDelivercityid(cid);
VendorCity vendorCity = new VendorCity();
vendorCity.setVendorcity(city);
vendorCity.setName(vendorname);
vendorCity.setVendorid(vendor);
vendorCity.setCreatedby(loginuser);
VendorCity delivercity = vendorcitydao.save(vendorCity);
if (delivercity != null) {
CustomResponse.setResponse(delivercity);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
CustomResponse.setResponseMessage(CustomStatus.SuccessMsg);
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Below is script for button click to add cities into div when Ajax success:
function addcity(){
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
var url = "../api/setdeliverycity";
$.post(url,{
delivercityid : delivercityid,
vendorid : vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
var vid = vendor.vendorcityid;
var city = vendor.vendorcity.city;
var citydiv = "";
var cityid = vendor.vendorcity.delivercityid;
var citylistlength = city.length;
if(citylistlength > 0) {
citydiv = citydiv+"<div>"+city+" <i class=\"fa fa-times\" onclick=\"removecity('"+cityid+"')\"></i></div>";
}else{
citydiv = citydiv+"<div style=\"text-align: center; float: left; margin-left: 40%; font-size: medium; font-weight: bolder; background: blanchedalmond;\"><span>Choose city from list</span></div>";
}
$('#citydivid').append(citydiv);
$('#cid').val(cityid);
$('#vendorcityid').val(vid);
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
You can check on page load if there is any data inside your localStorage or not .If yes you can get that datas and call your ajax to execute further codes and inside this ajax call if data are successfully appended inside your DOM your can clear previous data and save new data i.e : vendorid..etc inside localStorage.
Here , is sample code which should work :
$(function() {
//check if the localStorage is not null
if (localStorage.getItem("delivercityid") != null) {
var delivercityid = localStorage.getItem("delivercityid"); //get that value
var vendorid = localStorage.getItem("vendorid");
ajax_call(vendorid, delivercityid); //call function
localStorage.clear(); //clear from here after page load..
}
});
function addcity() {
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
ajax_call(vendorid, delivercityid)
}
function ajax_call(vendorid, delivercityid) {
var url = "../api/setdeliverycity";
$.post(url, {
delivercityid: delivercityid,
vendorid: vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
//..
//other codes..
localStorage.setItem("vendorid", vendorid);
var delivercityid_datas = JSON.parse(localStorage.getItem("delivercityid")) || []; //all datas
delivercityid_datas.push(delivercityid); //push new data inside localstorage
localStorage.setItem("delivercityid", JSON.stringify(delivercityid_datas)); //reinitalze again
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
I have a script that makes an ajax call to an action in the controller and save some records.
The whole process is working fine but my little issue is to redirect to another page after saving records successfully.
With my code below, the records were added successfully with an alert indicating as it is described in the code "msg + "Courses were Registered"". Rather than doing that I want it to redirect to an action.
Javascript code:
<input type="submit" value="Register Courses" id="register" class="btn btn-rose" />
<script>
$(document).ready(function () {
$("#register").click(function () {
var items = [];
$('input:checkbox.checkBox').each(function () {
if ($(this).prop('checked')) {
var item = {};
item.CourseID = $(this).val();
item.CourseCode = $(this).parent().next().html();
item.CourseName = $(this).parent().next().next().html();
item.Units = $(this).parent().next().next().next().html();
items.push(item);
}
});
var options = {};
options.url = "/Course/SaveCourse";
options.type = "POST";
options.dataType = "json";
options.data = JSON.stringify(items);
options.contentType = "application/json; charset=utf-8;";
options.success = function (msg) {
alert(msg + " Courses were Registered");
};
options.error = function () {
alert("Error while Registering Courses");
};
$.ajax(options);
});
});
</script>
Controller
[HttpPost]
public IActionResult SaveCourse([FromBody]List<CourseRegModel> courseIDs)
{
var user = HttpContext.Session.GetString("currentUser");
if (user == null)
{
return RedirectToAction("Login", "Account");
}
ViewBag.student = user;
var pendingPayment = (from row in _context.BursaryTransactions where row.MatricNo == user && row.ResponseCode == "021" select row).Count();
if (pendingPayment > 0)
{
return RedirectToAction("PaymentSummary", "Student");
}
var student = _context.StStudentInfo.Include(m =>m.AdmInstProgramme.AdmInstDepartment).Include(m =>m.AdmInstClassLevels).FirstOrDefault(m => m.MatricNo == user);
var session = _context.AdmInstProgrammeTypeSession.Include(m => m.AdmInstSemesters).Include(m => m.AdmInstSessions).Include(m => m.AdmInstProgramType).Where(m => m.IsActive == true).FirstOrDefault(m => m.ProgramTypeId == student.ProgrammeTypeId);
foreach (CourseRegModel courseID in courseIDs)
{
courseID.Level = student.AdmInstClassLevels.ClassLevel;
courseID.Semester = session.AdmInstSemesters.Semester;
courseID.Session = session.AdmInstSessions.SessionName;
courseID.Department = student.AdmInstProgramme.AdmInstDepartment.Department;
_context.CourseRegModel.Add(courseID);
}
int courses = _context.SaveChanges();
return Json(courses);
}
Objective is to return RedirectToAction("MyCourses","Courses"); after SaveChanges();
If you want to redirect to another action method why would you use AJAX? But I think you can work around that by performing the redirect in the client side AJAX after it is successfully receive a response you use JavaScript to do the redirect
You can simply redirect your page inside ajax's success handler,
options.success = function (msg) {
window.localtion.href = "/Courses/MyCourses";
// or window.location.href = '#url.Action("MyCourses","Courses")';
};
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>
}
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>
}