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();
Related
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'm trying to use HtmlUnit to get data fom a web site,
so far i managed to enter the data needed in order to login (username & password).
The problem begins with the fact that the website login form dosent have a submit button, instead there is an href that has an onClick JavaScript function (onclick="login_submit())
that verify data and then call window.location = "index.php";
So i tried clicking the href using:
HtmlAnchor anchor = page.getAnchorByText("כניסה");
page = anchor.click();
and tried:
page.executeJavaScript(javaScriptCode);
but the page variable dosent get the expected page, it got the same url as before clicking and there is no redirection. Once the login_submit() function is called there is a label that indicates " login.." but nothing happens from there.
Here is the code:
// javascript login_submit() -- this is not my website and not my JS code so ive deleted some things:
function login_submit()
{
if(!LOGIN_SUBMIT_PROCESSED)
{
var approved = true;
var admin_user_username_field = document.getElementById('admin_user_username');
var admin_user_username_error = document.getElementById('admin_user_username_error');
var admin_user_password_field = document.getElementById('admin_user_password');
var admin_user_password_error = document.getElementById('admin_user_password_error');
admin_user_username_field.className = "login_form_field_input_text";
admin_user_username_error.style.display = 'none';
admin_user_password_field.className = "login_form_field_input_text";
admin_user_password_error.style.display = 'none';
if(admin_user_username_field.value.length == 0)
{
//do something
}
if(admin_user_password_field.value.length == 0)
{
//do something
}
if(approved)
{
LOGIN_SUBMIT_PROCESSED = true;
document.getElementById("login_form_options").style.display = "none";
document.getElementById("login_form_process").style.display = "";
var http_request = new XHConn();
http_request.connect(
"login_submit.php?cache="+string_unique(),
"POST",
"form_anti_bot_code="+encodeURIComponent(form_anti_bot_code_field.value)
+ "&admin_user_username="+encodeURIComponent(admin_user_username_field.value)
+ "&admin_user_password="+encodeURIComponent(admin_user_password_field.value),
function(response,callback_data)
{
if(response.readyState == 4)
{
if(response.status == 200)
{
//alert(response.responseText);
try
{
var json_response = JSON.parse(response.responseText);
if(json_response["error_code"] == "0")
{
window.location = "index.php";
}
else
{
//do something
}
}
catch(error)
{
alert(error);
}
}
LOGIN_SUBMIT_PROCESSED = false;
}
},
null
);
}
}
}
Java code:
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setCssEnabled(true);
//webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = (HtmlPage) webClient
.getPage(url);
HtmlForm form = page.getFormByName("login_form");
form.getInputByName("admin_user_username").setValueAttribute("XXXXX");
HtmlInput passWordInput = form.getInputByName("admin_user_password");
passWordInput.removeAttribute("disabled");
passWordInput.setValueAttribute("XXXXXX");
HtmlAnchor anchor = page.getAnchorByText("Login");
page = anchor.click();
System.out.println(page.getBody().asText());
webClient.close();
}
I know for a fact after some testing that the login data is ok, href is clicked and there is an indicator that login is being proccesed.
the main problem is that its not redirecting and dont get the "index.php" page.
Try this and it should do the trick:
WebWindow window = page.getEnclosingWindow();
This might do the trick:
final HtmlPage page2 = page.getElementById("Login_Button").click();
Ok so the scenario is currently I am populating a drop down list from my model with the following code
ViewBag.LeaseCompanyID = new SelectList(ContractModelEntity.system_supplier.Where(x => x.Type == "Lease"), "CompanyID", "Name", data.LeaseCompanyID);
This works perfectly, however on my form I have a button located next to the drop down list which adds another option in the database, using ajax and a modal popup.
The controller code for this is here
[HttpPost]
public JsonResult AddSupplier([Bind(Include="Name,Type")] system_supplier data)
{
if (ModelState.IsValid)
{
ContractModelEntity.system_supplier.Add(data);
ContractModelEntity.SaveChanges();
return Json(0, JsonRequestBehavior.AllowGet);
}
return Json(1, JsonRequestBehavior.AllowGet);
}
When the new option is added into the database I then need to refresh my dropdownlist to get this new data (currently if I refresh the page I can see the new option). I am using minimalect plugin for the drop downs.
Does anybody know a way of updating this minimalect list, there must be a way of building the list through an ajax call which returns some JSON data.
Thanks in advance for your help
OK so after doing a bit of research here is my solution, hopefully it will help other poeple. Someone might even have a cleaner solution.
I first created a jsonresult controller method which looked like this
[HttpGet]
public JsonResult RetreiveSuppliers(string contractType)
{
var supplierData = ContractModelEntity.system_supplier.Where(x => x.Type == contractType);
var result = new List<object>();
foreach (var x in supplierData)
{
result.Add(new { Id = x.CompanyID, Name = x.Name });
}
return Json(result, JsonRequestBehavior.AllowGet);
}
That got me the data from the database. then I created a javascript on the page which looks like this
$("body").on("click", "#btn_InsertNewSupplier", function () {
var supForm = $("#addSupData");
$.ajax({
url: "#Url.Action("AddLeaseSupplier", "Contract")",
data: supForm.serialize(),
type: "POST",
success: function (result) {
if (result === 0) {
var inst = $.remodal.lookup[$('[data-remodal-id=modal_AddSupplier]').data('remodal')];
inst.close();
NotificationAlert("success", "New Supplier Created");
GetNewSupplierList();
} else {
NotificationAlert("error", "Failed Adding New Supplier");
}
}
});
});
function GetNewSupplierList() {
var actionurl = "#Url.Action("RetreiveSuppliers", "Contract", new { contractType = "Lease"})";
$.getJSON(actionurl, tempdata);
}
function tempdata(response) {
if (response != null) {
var html = "";
for (var i = 0; i < response.length; i++) {
html += '<option value="' + response[i].Id + '">' + response[i].Name + '</option>';
}
$("#LeaseCompanyID").html(html);
}
}
So once the ajax call is successful it will trigger the GetNewSupplierList function which calls my controller method and returns some JSON data. Once that is returned it calls tempdata, which builds the new HTML for my select picker, once that is built it updates the html on the selectpicker id.
Works like a charm!!!
Thanks to everyone who took a look at this post.
I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});