Pagination in .Net Core PartialView - javascript

I have a Partial View in which I load a pager for pagination.
The functionality of the pagination works, as the link changes as follows: http://localhost:1048/Trip -> http://localhost:1048/Trip?page=2 but it seems like my "request" to load the "next page" doesn't work as intended.
PartialView
//Here is a table view that
//that requires pagination.
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<ul class="pager">
<li>
<a asp-action="Index"
asp-route-page="#(Model.PageIndex - 1)"
class="btn btn-default #prevDisabled btn">
Previous
</a>
</li>
<li>
<a asp-action="Index"
asp-route-page="#(Model.PageIndex + 1)"
class="btn btn-default #nextDisabled btn">
Next
</a>
</li>
</ul>
I assume that my link is wrong (asp-action="Index"), but I have no idea what else to have it "navigate to" (I tried changing it to my controller function - but that result was very much unwanted) as I am still fairly new to .Net. Also I know that I have an error in my Controller function where I load page 1 always. How do I check whether a page is input to the function? (something like if (page == null) { page = 1 }) The function that loads my Partial View is as follows:
Controller function
[HttpGet]
public async Task<IActionResult> TripTable(int? page)
{
var trips = from t in _tripcontext.Tripmetadata select t;
page = 1;
int pageSize = 20;
return PartialView("PartialTripsView", await PaginatedList<Tripmetadata>.CreateAsync(trips.AsNoTracking().OrderBy(t => t.Tripid), page ?? 1, pageSize));
}
UPDATE
I guess I forgot to mention that whenever I use the Next button it just refreshed the entire Index page (without the Partial View in it). The Partial View is loaded when a button on the Index page is clicked, so when the page refreshes the Partial View is not present anymore.

I managed to figure it out after quite some reading online:
First of I changed my PartialView to the following:
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<ul class="pager">
<li>
<a id="prev" data-url="#Url.Action("TripTable", "Trip")" data-id="#Model.PageIndex" class="btn btn-default #prevDisabled btn">
Previous
</a>
</li>
<li>
<a id="next" data-url="#Url.Action("TripTable", "Trip")" data-id="#Model.PageIndex" class="btn btn-default #nextDisabled btn">
Next
</a>
</li>
</ul>
If someone else is stuck on the same problem I got most of my code from the Microsoft Docs on creating a pagination here.
My controller method was changed only a little:
public async Task<IActionResult> TripTable(int? page)
{
var trips = from t in _tripcontext.Tripmetadata select t;
int pageSize = 10;
return PartialView("PartialTripsView", await PaginatedList<Tripmetadata>.CreateAsync(trips.AsNoTracking().OrderBy(t => t.Tripid), page ?? 1, pageSize));
}
And in the bottom of my PartialView I added the following:
<script>
$("#prev").click(function () {
var _this = $(this);
var prevPage = _this.data('id') - 1;
$("#TripPartial").load(_this.data('url'), { page: prevPage }, function () {
});
});
$("#next").click(function () {
var _this = $(this);
var nextPage = _this.data('id') + 1;
$("#TripPartial").load(_this.data('url'), { page: nextPage }, function () {
});
});
</script>

Related

Javascript code within <script> tag being rendered in the page

I am fairly new to the js and the referencing of the script. I have a particular js code in my partial view. The actual code is:
<script>
var bID = #businessIDScript;
var gID = #groupIDScript;
var dID = #departmentIDScript;
var aID = #areaIDScript;
if (!(aID > 0)) {
$("#createIdlerButton").attr("disabled", "disabled");
$("#importIdlerButton").attr("disabled", "disabled");
}
if (#sapEnabled == true) {
$("#sapIdlerReport").show();
$("#sapIdlerReportAnchor").removeAttr('onClick');
$("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
} else {
$("#sapIdlerReport").hide();
}
</script>
complete razor view page is:
#using PDS.Domain.EF6.Resources.Web
#using Kendo.Mvc.UI
#using PDS.Web.Areas.PlannedInspections.Models;
#using PDS.Web.Utils;
#{
var sapEnabled = ViewBag.SAPEnabled.ToString().ToLower();
var isLaidOutHide = (string)ViewData["isLaidOutHide"];
var EnforceUserDropDown = (string)ViewData["EnforceUserDropDown"].ToString().ToLower();
var CurrentLevelIsDashboard = false;
bool.TryParse(ViewData["CurrentLevelIsDashboard"].ToString(), out CurrentLevelIsDashboard);
var WorkOrderDashboardParameters = ViewData["WorkOrderDashboardParameters"] != null ?
(WorkOrderDashboardParameters)ViewData["WorkOrderDashboardParameters"] : null;
var importDataName = ViewData["importDataName"]?.ToString() ?? "";
var importTemplateUrl = ViewData["importTemplateUrl"]?.ToString() ?? "";
var importActionUrl = ViewData["importActionUrl"]?.ToString() ?? "";
var areaId = ViewData["areaId"]?.ToString().Trim() ?? "";
var areaIDScript = string.IsNullOrEmpty(areaId) ? "0" : areaId;
var breadcrumbTitle = ViewData["breadcrumbTitle"]?.ToString().Trim() ?? "";
var areaIdStr = ViewData["areaId"]?.ToString().Trim() ?? null;
var departmentIdStr = ViewData["departmentId"]?.ToString().Trim() ?? null;
var groupIdStr = ViewData["groupId"]?.ToString().Trim() ?? null;
var businessIdStr = ViewData["businessId"]?.ToString().Trim() ?? null;
var businessId = "";
if (!string.IsNullOrEmpty(businessIdStr))
{
businessId = businessIdStr;
}
else
{
using (var context = PDS.Domain.EF6.EF.CcMSEntitiesv6.CreateForUser(User))
{
if (!string.IsNullOrEmpty(groupIdStr))
{
var id = int.Parse(groupIdStr);
businessId = context.vwAreas.FirstOrDefault(x => x.GroupID == id)?.BusinessID.ToString() ?? "";
}
else if (!string.IsNullOrEmpty(departmentIdStr))
{
var id = int.Parse(departmentIdStr);
businessId = context.vwAreas.FirstOrDefault(x => x.DepartmentID == id)?.BusinessID.ToString() ?? "";
}
else if (!string.IsNullOrEmpty(areaIdStr))
{
var id = int.Parse(areaIdStr);
businessId = context.vwAreas.FirstOrDefault(x => x.AreaID == id)?.BusinessID.ToString() ?? "";
}
}
}
var businessIDScript = string.IsNullOrEmpty(businessId) ? "0" : businessId;
var groupIDScript = string.IsNullOrEmpty(groupIdStr) ? "0" : groupIdStr;
var departmentIDScript = string.IsNullOrEmpty(departmentIdStr) ? "0" : departmentIdStr;
}
<div id="idler-grid-toolbar" class="toolbarGridContainer">
<div class="pull-left">
#(Html.Kendo().DropDownList()
.Name("GridFilter")
.HtmlAttributes(new { data_column = "IsAtRisk" })
.Items(items =>
{
items.Add().Text(IdlerManagement.IdlerTag_Dropdown_HideReplaced).Value("active");
items.Add().Text(General.All).Value("all");
items.Add().Text(IdlerManagement.IdlerTag_Dropdown_AtRisk).Value("atrisk");
})
.Events(ev => ev.Change("PDS.IdlerManagement.activeIdlerDashboardFilterChanged"))
)
#(Html.Kendo().DropDownList()
.Name("IdlerGridFilter")
.HtmlAttributes(new { data_column = "Idler" })
.Items(items =>
{
items.Add().Text(IdlerManagement.Idlers).Value("true");
items.Add().Text(IdlerManagement.Structures).Value("false");
items.Add().Text(General.All).Value("all");
})
.Events(ev => ev.Change("PDS.IdlerManagement.activeIdlerDashboardFilterChanged2"))
)
#if (!CurrentLevelIsDashboard)
{
<span class="pull-right">
<button type="button" id="schematicsButton" class="btn btn-default" title='#IdlerManagement.Schematics_Button' onclick="PDS.IdlerManagement.editSchematic(this, '#areaId')">
#IdlerManagement.Schematics_Button
</button>
</span>
}
#if (User.IsInRole("Power User") || User.IsInRole("Business Administrator") || User.IsInRole("System Administrator"))
{
<div class="pull-right">
<div class="dropdown shutdown-planner-dropdown">
<button type="button" id="shutdownPlannerTags" class="btn btn-default dropdown-toggle" title='#IdlerManagement.ShutdownPlanner_Button' data-toggle="dropdown">
#IdlerManagement.ShutdownPlanner_Button
<span role="button" unselectable="on" class="k-select" aria-label="select">
<span class="k-icon k-i-arrow-60-down"></span>
</span>
</button>
<ul class="dropdown-menu dropdown-menu-right" style="transform:translate3d(0px, 51px, 0px); overflow-y:auto">
<li>
#IdlerManagement.ShutdownPlanner_Button_Add
</li>
<li>
#IdlerManagement.ShutdownPlanner_Button_Remove
</li>
</ul>
</div>
</div>
#Html.Partial("_IdlerShutdownPlannerTemplate")
}
#if (!User.IsInRole("Read Only User"))
{
<button class="btn btn-default " onclick="PDS.IdlerManagement.closeOutIdlerTags(this, #EnforceUserDropDown, '#User.Identity.Name')" disabled="disabled" id="closeOutIdlerTags">#IdlerManagement.IdlerTag_Button_CloseOut</button>
<button class="btn btn-default #isLaidOutHide" onclick="PDS.IdlerManagement.laidOutIdlerTags(this, #EnforceUserDropDown, '#User.Identity.Name')" disabled="disabled" id="laidOutIdlerTags">#IdlerManagement.IdlerTag_Button_LaidOut</button>
}
</div>
#if (WorkOrderDashboardParameters != null)
{
<span class="pull-right">
<button type="button" data-role="close" id="viewAsset" class="btn btn-default" title="#General.Close" onclick="PDS.Common.UrlHistory.navigateBack()">
<i class="fa fa-times"></i>
</button>
</span>
}
<span class="pull-right">
#Html.Partial("_QuickReport", new ViewDataDictionary() { { "groupName", "Idler Management" } })
</span>
#Html.Partial("_ImportExportButtons", new ViewDataDictionary() { { "DownloadTemplateUrl", $"/GlobalImportExport/ImportWizard/DownloadImportTemplateByEntity?entityName=IdlerTag" }, { "EntityName", "IdlerTag" } })
#if (!User.IsInRole("Read Only User"))
{
if (!CurrentLevelIsDashboard)
{
<div class="pull-right">
<div class="dropdown create-idlerstructure-button-dropdown">
<button type="button" id="createIdlerButton" class="btn btn-default dropdown-toggle" title="#IdlerManagement.IdlerTag_Tooltip_CreateRecord" data-toggle="dropdown"><i class="fa fa-plus"></i></button>
<ul class="dropdown-menu dropdown-menu-right">
<li>
#IdlerManagement.IdlerTag_Button_CreateIdler
</li>
<li>
#IdlerManagement.IdlerTag_Button_CreateStructure
</li>
</ul>
</div>
</div>
}
}
</div>
#Html.Partial("_ImportTemplate", new ViewDataDictionary() { { "importTemplateUrl", importTemplateUrl }, { "importActionUrl", importActionUrl } })
<script>
var bID = #businessIDScript;
var gID = #groupIDScript;
var dID = #departmentIDScript;
var aID = #areaIDScript;
if (!(aID > 0)) {
$("#createIdlerButton").attr("disabled", "disabled");
$("#importIdlerButton").attr("disabled", "disabled");
}
if (#sapEnabled == true) {
$("#sapIdlerReport").show();
$("#sapIdlerReportAnchor").removeAttr('onClick');
$("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
} else {
$("#sapIdlerReport").hide();
}
</script>
The display looks like this: As you can see in the image below some of the js code is being rendered in the main page. I am having hard time fixing this issue.
Note: There is no issue with the functionality of the code it works perfectly fine. Even tried doing console.log("Hello World"). Throws the same dark half baked js in the page. Any help would be appreciated.
Thank you in advance.
What i have tried:
Initially, I thought this issue was due to some missing tags and closure in html tags but i fixed those issues and resolved up the console errors and warnings that i was getting for those tags. Also, i found out that "display none" on the script tag fixed that issue but my senior won't allow it saying its not the solution just a hack. I don't have a clue what is causing this issue because there are no warning nor any errors in VS. also i tried doing document.Ready function for this script but that failed miserably as well. Now i am out of depth and have no idea what is causing this error. Another solution i discovered was if i move this whole script inside a new <div> tag, it resolves the issue.
Expectation:
--> The js should not be rendered in the page.
Below will help
can you please try it with script rendering section on you layout page and then render your script on that scope.
// use this on your layout page-- bottom of page once all plugin scripts are rendered
#RenderSection("scripts", required: false)
// use below on your partial
#section scripts{
<script type="text/javascript">
var bID = #businessIDScript;
var gID = #groupIDScript;
var dID = #departmentIDScript;
var aID = #areaIDScript;
if (!(aID > 0)) {
$("#createIdlerButton").attr("disabled", "disabled");
$("#importIdlerButton").attr("disabled", "disabled");
}
if (#sapEnabled == true) {
$("#sapIdlerReport").show();
$("#sapIdlerReportAnchor").removeAttr('onClick');
$("#sapIdlerReportAnchor").attr('onClick', 'PDS.IdlerManagement.sapIdlerReport(' + bID + ',' + gID + ',' + dID + ',' + aID + ')');
} else {
$("#sapIdlerReport").hide();
}
}
It looks like the page is rending the script tag as html.
A quick and simple fix would be to hide the script tag like so:
<script style="display:none;">
If you could move that functionality outside of the razor page and into a dedicated javascript/typescript page it would probably fix the render issue aswell.
Have you tried moving the script to a different location and see what happens? Kendo template might be rendering that JavaScript snippet to the datagrid columns/header as text. I guess what you can do is do first is do a trial and error determine where the code would work and the same time wont render as text. Maybe somewhere common like the layout page or something? Afterwards you can then do a proper fix like where the code should be best placed.

ASP.NET Core - change form action to list options in view

I have controller for changing website language, saving cookie and returning url.
`
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
namespace Website.Controllers;
public class CultureController : Controller
{
[HttpPost]
public IActionResult SetCulture(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(365) }
);
return LocalRedirect(returnUrl);
}
}
`
And in View I need create html list for better user experience but I don't understand how to change from 'form' to 'list' or how to submit changes and return url
`
#using Microsoft.AspNetCore.Localization
#using Microsoft.Extensions.Options
#inject IOptions<RequestLocalizationOptions> LocalizationOptions
#{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocalizationOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.EnglishName })
.ToList();
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}{Context.Request.QueryString}";
}
<!-- FROM FORM -->
<div class="language">
<form asp-controller="Culture" asp-action="SetCulture" asp-route-returnUrl="#returnUrl" class="form-horizontal nav-link text-dark">
<select name="culture"
onchange="this.form.submit();"
asp-for="#requestCulture.RequestCulture.UICulture.Name"
asp-items="cultureItems">
</select>
</form>
</div>
<!-- TO LIST -->
<div class="language-toggle">
<i class="fas fa-language"></i>
<ul class="language-menu">
#foreach (var item in LocalizationOptions.Value.SupportedUICultures)
{
<li>#item.Name.ToUpper()</li>
}
</ul>
</div>
`
I tried with anchor tag helper but without success
output
Output
I can get current url in view and append ?culture=en and that changes language and stays on current page but does not save cookie so every time user goes to different page website is in native language not in user selected language.
You can achieve that with something like this:
<head>
<script type="text/javascript">
function submitCulForm(val) {
document.getElementById("cultureVal").value = val;
var hh = document.getElementById("cultureForm");
hh.submit();
return false;
}
</script>
</head>
Then
<form asp-controller="Culture" id="cultureForm" asp-action="SetCulture" asp-route-returnUrl="#returnUrl" class="form-horizontal nav-link text-dark">
<input id="cultureVal" type="hidden" name="culture" value="-">
<div class="language-toggle">
<i class="fas fa-language"></i>
<ul class="language-menu">
#foreach (var item in LocalizationOptions.Value.SupportedUICultures)
{
<li>#item.Name.ToUpper()</li>
}
</ul>
</div>
</form>
If you try to pass the value with herf,you shouldn't add [HttpPost] Attribute on your controller.
I tried with the codes in your controller,it works well,I'll show what I've tried and hopes it could help
in View:
<div>
<a asp-action="SetCulture" asp-route-culture="zh-CN">zh-CN</a>
<a asp-action="SetCulture" asp-route-culture="en-US">en-US</a>
</div>
<script>
var cookie = document.cookie
console.log(cookie)
</script>
in Controller:
public IActionResult SetCulture(string culture)
{
if (culture != null)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(365) });
return RedirectToAction("Create");
}
return BadRequest();
}
Configure in startup:
services.AddControllersWithViews()
.AddDataAnnotationsLocalization(
options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResources));
});
...............
var supportedCultures = new[] { "en-US", "zh-CN" };
var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
created an empty class called SharedResources
and the resourcefile:
The Result:
It just performed as the document,and if you tried with mulipule providers,you could try to change request culture providers order which has been mentioned in the document

Ajax search doesn't work the second time (ASP.NET MVC)

I have a problem changing items after searching.
I looked at similar threads but found no solution there :(
It looks like the first time the page loads well - the first time the entire Index.cshtml page is loaded which contains a collection of books in the selected category.
There is a search engine on the page - after searching for "manual" - ajax correctly replaces elements with those containing "manual" in the name.
Then when I enter something into the search engine a second time (for example "exercises") - the content of the page does not change any more.
I tried to debug and I see that new items are correctly downloaded from the database - the condition "if (Request.IsAjaxRequest ())" is true and the items are passed to partial view - there the "foreach" loop goes through them. Unfortunately, after _Partial, nothing happens.
I can't find a mistake - the strangest thing is that the first ajax call works fine - only the second (and subsequent) bad.
CatalogController.cs
public ActionResult Index(string categoryName = null, string searchQuery = null)
{
if (categoryName == null)
categoryName = (db.Categories.Find(1)).Name;
var category = db.Categories.Include("Books").Where(x => x.Name.ToLower() == categoryName).Single();
var books = category.Books.Where(x => (searchQuery == null || x.Title.ToLower().Contains(searchQuery.ToLower()) || x.SubTitle.ToLower().Contains(searchQuery.ToLower()) || x.Level.ToLower().Contains(searchQuery.ToLower())) && !x.Inaccessible);
if (Request.IsAjaxRequest())
return PartialView("_PartialBooksList", books);
else
return View(books);
}
Index.cshtml
<form class="o-search-form" id="search-form" method="get" data-ajax="true" data-ajax-target="#booksList">
<input class="o-search-input" id="search-filter" type="search" name="searchQuery" data-autocomplete-source="#Url.Action("SearchTips")" placeholder="Search" />
<input class="o-search-submit" type="submit" value="" />
</form>
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
#section Scripts
{
<script src="~/Scripts/jquery-3.5.0.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
var setupAutoComplete = function () {
var $input = $(this);
var options =
{
source: $input.attr("data-autocomplete-source"),
select: function (event, ui) {
$input = $(this);
$input.val(ui.item.label);
var $form = $input.parents("form:first");
$form.submit();
}
};
$input.autocomplete(options);
};
var ajaxSubmit = function () {
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function (result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
return false;
};
$("#search-filter").each(setupAutoComplete);
$("#search-form").submit(ajaxSubmit);
});
</script>
}
_PartialBooksList
#model IEnumerable<ImpressDev.Models.Book>
#using ImpressDev.Infrastructure
<div class="row">
#foreach (var book in Model)
{
<div class="col-12 col-xl-4">
<a class="o-shop-link" href="#Url.Action("Details", "Catalog", new { bookId = book.BookId })">
<div class="o-shop-item">
<img class="o-shop-img" src="#Url.BookPhotoSourcePath(book.PhotoSource)" />
<div class="o-shop-text">
<h2>#book.Title</h2>
<h6>#book.SubTitle - #book.Level - <b>#book.Price zł.</b></h6>
+ Add to cart
</div>
</div>
</a>
</div>
}
</div>
Please help
I am not sure if this is the case, but try to change this code:
$($targetElement).replaceWith($newContent);
To this:
$($targetElement).html($newContent);
I think the problem is the div element with id="booksList" is replaced after first search. So you don't have this element in the second search.
I looked through the code step by step and found a solution to my problem.
In the first search, replace id="booksList"
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
partial view in which there was only without id = booksLists.
In the next search there was no ID in this place and there was nothing to replace.

Angular.js run ng-show function after scope is updated

I have a poll application, in which a user can vote for an option in a given poll. in the html template, i use ng-show to show weather the user has voted for this option or this poll or if its an unvoted poll for the user:
<div data-ng-repeat="option in poll.poll_options" class="list-group-item">
<span data-ng-if="option.option_thumb == '2'" class="glyphicon glyphicon-thumbs-up"></span>
<span data-ng-if="option.option_thumb == '1'" class="glyphicon glyphicon-thumbs-down"></span>
<div data-ng-show="optionVoted(option,authentication.user._id)">
<span data-ng-bind="option.option_text"></span>
</div>
<div data-ng-hide="optionVoted(option,authentication.user._id)">
<div data-ng-show="pollVoted(poll._id,votes)">
<a data-ng-click="updateVote()">
<span data-ng-bind="option.option_text"></span> - update
</a>
</div>
<div data-ng-hide="pollVoted(poll._id,votes)">
<a data-ng-click="createVote(poll,option,authentication.user._id,$index)">
<span data-ng-bind="option.option_text"></span> - new
</a>
</div>
</div>
<span class="option-votes"> - {{option.votes.length}}</span>
</div>
these are the above mentioned functions to determine if the option / poll has been voted by the user:
// check if option is voted
$scope.optionVoted = function(option,userId){
for (var i = 0; i < option.votes.length; i++){
if (option.votes[i].user === userId){
return true;
}
}
};
//check if poll is voted
$scope.pollVoted = function(pollId,votes){
for (var i = 0; i < votes.length; i++){
if (votes[i].poll === pollId){
return true;
}
}
}
and here is the function to create a new vote:
// create a vote
$scope.createVote = function(poll,option,userId,index){
var vote = new Votes({
user:userId,
poll:poll._id,
poll_option:option._id
});
vote.poll_option_id = option._id;
vote.$save(function(vote){
option.votes.push(vote);
$scope.$apply();
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
}
what happens on the front end, is that the option which has been now voted is updated (not showing an a tag anymore). what i need, is that the other options in the poll will update as well, and now instead of create() they will show update(), without refreshing the page.
how can I get the other html DOM elements of options in the poll to update?
In html, replace the functions in ng-show by an object property :
ng-show="option.voted", for example.
and update option.voted in createVote function.
(adapt this with userId etc.)
Make sure you are pushing the new vote onto the correct object in the scope. It looks like you are displaying data from $scope.poll.poll_options in your view, but you are adding to options.votes in your createVote function.

javascript stop onclick function propagation

I am developing an application in django, but I have a problem with JAVASCRIPT.
By the way I am new in web development, I am beginninng to learn python an javascript.
I have an html table rendered from django and I insert a drop down button in the first column of the table with this function
function GetAllValues() {
var tbl = document.getElementById("myTable");
for (var i = 1; i < tbl.rows.length; i++){
tbl.rows[i].cells[3].innerHTML = '<div class="btn-group">
<button type="button" class="btn btn-xs btn-primary dropdown-toggle" data-toggle="dropdown">'
+ tbl.rows[i].cells[3].innerHTML +
'<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a id="configura" onclick="configp();" >Configura</a>
</li>
<li><a id="recepcion" onclick="param(); return false;">Recepcion de Archivos</a>
</li>
<li><a id="carga" onclick="cargaf(); return false;">Carga de Archivos</a>
</li>
<li><a id="conci" onclick="concif(); return false;">Detalle Conciliacion</a>
</li>
</ul>
</div>'
}
Every button call a different function to redirect to another page with some forms.
I use function like this to redirect to the forms:
function configp(event){
var tbl = document.getElementById("myTable");
var rows = tbl.rows;
var argu = "";
for (var i = 0; i < rows.length; i++){
rows[i].onclick = function(){
idpro = this.cells;
argu = "?idprov="+idpro[0].innerHTML;
window.location = "/config/"+argu;
}
}
}
the function take some values of the table and pass it as argument to the url.
(why I am redirecting like this. Long history)
My problem is the onclick propagation.
I try putting return false before the last "}" in the configp() function and doesn't work.
I try to stop the propagation using event.preventdefault() and e.stopPropagation() any of those method can stop the propagation.
How can I stop the onclick propagation in the dropdown button
Any advice
THANKS IN ADVANCE
UPDATE
In simple words: when I click in the first option of the dropdown the function redirect me to the page that i want. if get back to the original page, no matters what option I clicked always redirect to the page where I was redirected to the page assigned to the first option. and the onclick event bubble in all the levels of the dropdown

Categories