I have a html document but it's size is about 5MB.
Here is my code "../Product/index?page=1" it generates 5MB html :
Plugin url : http://andersonferminiano.com/jqueryscrollpagination/
<script type="text/javascript">
$(function () {
$('#content').scrollPagination({
'contentPage': '../Product/index?page=1',
'contentData': {},
'scrollTarget': $(window),
'heightOffset': 10,
'beforeLoad': function () {
$('#loading').fadeIn();
},
'afterLoad': function (elementsLoaded) {
$('#loading').fadeOut();
var i = 0;
$(elementsLoaded).fadeInWithDelay();
if ($('#content').children().size() > 100) {
$('#nomoreresults').fadeIn();
$('#content').stopScrollPagination();
}
}
});
$.fn.fadeInWithDelay = function () {
var delay = 0;
return this.each(function () {
$(this).delay(delay).animate({ opacity: 1 }, 200);
delay += 100;
});
};
});
</script>
<!--_____________________________________________________________________-->
#{
// here is "Product/index" Code
if (Request.QueryString.HasKeys())
{
int iPage = Request.QueryString["page"].AsInt();
using (var db = new PNUBOOKIR.Models.KowsarSiteEntities())
{
var queries = from n in db.vwGood
select n;
long counter = 0;
for (int i = 1; i <= iPage; i++)
{
foreach (var q in queries)
{
counter++;
<li style="opacity: 0; -moz-opacity: 0; filter: alpha(opacity=0);">
<p>
#counter
</p>
</li>
}
}
}
}
}
I don't want to load it complete when the scroll goes down it should load 10 other "li" element
I do not simulate so heavy page, but I have an other way to load page. Maybe, it can be a reference for you.
Separate each page request at action side, and return for only one page content.
Collect "style" content to css class, to reduce page content.
Improve performance of LINQ with PLINQ.
I notice the code output every page content.
var queries = from n in db.vwGood select n;
long counter = 0;
for (int i = 1; i <= iPage; i++)
{
foreach (var q in queries)
{
counter++;
}
}
I suggest you can
modify LINQ with Paging function.
Update LINQ as PLINQ to improve performance. I add AsParallel() after db.vwGood, I am not sure what db.vwGood instance and wish this modify can be good.
Not return HTML content in Razor View, but in Action.
Pseudo code of Action is as below,
// iAmount is record amount in each page.
int iAmount = 50;
// queries is only the iPage content
// but not all of content from page one to page iPage.
var queries = (from n in db.vwGood.AsParallel() select n)
.Skip(iPage - 1).Take(iAmount);
long counter = 0;
string strContent = string.Empty;
foreach (var q in queries)
{
counter++;
// Generate Cotnent here.
strContent += #"<li class='YourClassName'><p>#counter</p></li>"
}
return Content(strContent)
When ShowMore button is clicked, ShowMore_OnClick() is performanced.
<input type="button" style="width: 100%" id="BtnShowMore" value="MORE"
onclick="return ShowMore_OnClick();" />
This is JavaScript for Loading function.
I notice you do not use button to control content display, but scrollPagination. You can modify the JavaScript to suit with scrollPagination plugin. The thinking of code structure is same.
var PageNO = 1;
function ShowMore_OnClick() {
var BtnShowMore = document.getElementById("BtnShowMore");
BtnShowMore.value = "Loading...";
jQuery.post(
"/Home/GetHomeEventAjax/",
{ "PageNO": PageNO + 1 },
function (data, states) {
if (states == "success") {
var EventListArea = document.getElementById("EventListArea");
var newCommentItem = document.createElement("DIV");
newCommentItem.setAttribute("ID", "EventItem");
newCommentItem.innerHTML = data;
EventListArea.appendChild(newCommentItem);
PageNO = PageNO + 1;
BtnShowMore.value = "More";
}
}
);
}
Related
Is it possible to show the remaining session time in View in real-time when logged in ASP.NET MVC project? I didn't add any code to the question because I didn't come across any solution during my research.
I would do this in 2 steps, first pass the timeout value using a partial, so it can be reused. For e.g. read it from your Web.Config etc and pass it.
Then inside your view, you can add this script and adapt/modify the values.
#functions {
public int PopupShowDelay {
get { return 60000 * (Session.Timeout - 1); }
}
}
<script type="text/javascript">
window.SessionTimeout = (function() {
var _timeLeft, _popupTimer, _countDownTimer;
var stopTimers = function() {
window.clearTimeout(_popupTimer);
window.clearTimeout(_countDownTimer);
};
var updateCountDown = function() {
var min = Math.floor(_timeLeft / 60);
var sec = _timeLeft % 60;
if(sec < 10)
sec = "0" + sec;
document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;
if(_timeLeft > 0) {
_timeLeft--;
_countDownTimer = window.setTimeout(updateCountDown, 1000);
} else {
window.location = "Home/TimeOutPage";
}
};
var showPopup = function() {
_timeLeft = 60;
updateCountDown();
ClientTimeoutPopup.Show();
};
var schedulePopup = function() {
stopTimers();
_popupTimer = window.setTimeout(showPopup, #PopupShowDelay);
};
var sendKeepAlive = function() {
stopTimers();
ClientTimeoutPopup.Hide();
SessionTimeout.schedulePopup();
};
return {
schedulePopup: schedulePopup,
sendKeepAlive: sendKeepAlive
};
})();
</script>
#using (Html.BeginForm()) {
<p>
A timeout warning popup will be shown every #(Session.Timeout - 1) min.
</p>
#Html.Partial("TimeoutPartial")
}
I have display for my data like
#Html.DisplayFor(m=> m.UserName)
Result
John
I want to show only one character and hide the rest for user name data.
Result that is required
J######
Is there a quick way to display something like this, or will I have to write my own backend logic?
You can try to put #Html.DisplayFor(m=> m.UserName) into div;
and change the content of div with $(function(){}):
<div id="UserName">#Html.DisplayFor(m => m.UserName)</div>
<script>
$(function () {
var userName = document.getElementById('UserName').innerHTML;
var characters = userName.split('');
var newUserName = "";
if (characters.length > 0) {
newUserName = characters[0];
for (var i = 1; i < characters.length; i++) {
newUserName += '#';
}
}
document.getElementById('UserName').innerHTML = newUserName;
})
</script>
I need to render text elements, line elements, etc in the svg in blazor. So, I have created a jSinterop to perform this operations so that I can call the js methods wherever it is necessary.
My code snippet,
.razor
#inject IJSRuntime JsInterop
<svg id="parentElement">
#for (var i = 0; i < count; i++)
{
#RenderTextElements()
}
</svg>
#code {
int count = 10;
public object RenderTextElements()
{
return (JsInterop.InvokeAsync<object>("elementText", new object[] { }));
}}
My js files is
window.elementText = function () {
var svgElement = this.document.getElementById('parentElement');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('fill', 'black');
text.textContent = 'hello world';
svgElement.insertAdjacentElement('afterbegin', text)
}
This js method is invoked but text element did not append to DOM.
When I debugging through this method, I can see the element appended to DOM. Later, it is removed. I can't find where it is removed.
In svg you'll have to set the position for an element:
<script>
function insertElements() {
let parent = document.getElementById("parent");
for (let i = 0; i < 5; i++) {
let text = document.createElementNS('http://www.w3.org/2000/svg', "text");
text.setAttribute("x", 10);
text.setAttribute("y", 10 + 15 * i);
text.style.fill = "blue";
text.textContent = "text " + i;
parent.insertAdjacentElement("afterbegin", text);
}
}
function test() {
insertElements();
}
</script>
</head>
<body>
<button onclick="test()">Test</button>
<svg id="parent" width="200" height="200">
</svg>
</body>
I have a list in Razor Page which i want to use in java script.I'm using viewdata to send data to view VIewbag is working for some reason in razor page.
I'm using .net core 2.2
Things i already tried.
View
Things i already tried:
var a=#Model.listname
var stringArray = #Html.Raw (Json.Serialize(ViewData["Quest"]));` viewdata[Quest] contains list
string jsonn = JsonConvert.SerializeObject(quelist);`
and then send jsoon to view.
using custom class object and create create json object using Newtonsoft.Json and send to view
If you proposing ajex solution explain it a little as i dont know much about it or share a link for explanation
Razor page .cs file Commented the things that didn't
public async Task OnGetAsync()
{
ViewData["opt1"] = o1list;
ViewData["quest"] = quelist;
// string jsonn = JsonConvert.SerializeObject(quelist);
// ViewData["Jon"] = jsonn;
QuestionBank = await _context.QuestionBank
.Include(q => q.QuestionLevel)
.Include(q => q.QuestionStyle)
.Include(q => q.Teacher)
.Include(q => q.Topic).ToListAsync();
Answer = await _context.Answer.ToListAsync();
QSID = await _context.QSID.ToListAsync();
View
#{var name = (List<String>)ViewData["Quest"]; }
<script>
/*function test() {
var array = #Html.Raw(Json.Serialize(ViewData["Jon"]));
for(var i = 0; i < array.length; i++) {
alert(array[i]);
console.log(array[i]);
}
}
test();
*/</script>
</head>
<body>
#{
Model.run();
var name = (List<String>)ViewData["Quest"];
var nam = (List<String>)ViewData["opt1"];
int j = 0;
for (int i = 0; i <= 4; i++)
{
var a = name[i];
<p > #a </p>
<form action="">
<input type="radio" name="s" value="">#nam[j]<br>
#{j = j + 1; }
<input type="radio" name="s" value="">#nam[j]<br>
#{j = j + 1; }
<input type="radio" name="s" value="">#nam[j]<br>
#{j = j + 1; }
<input type="radio" name="s" value="">#nam[j]
#{j = j + 1; }
</form>
}
}
I expect to get a array containing my list or in json format
This is how I do it in a project I created:
<script>
var saleTypesById = #Html.Raw(JsonConvert.SerializeObject(Model.TypesById));
</script>
Where Model.TypesById is a Dictionary<long,SaleType>.
To use from javascript I call:
var selectedSaleType = saleTypesById[selectedId];
Then I can just call properties on it like selectedSaleType.Comission
This code requires #using Newtonsoft.Json; directive and a reference to the corresponding nugget package.
I follow the above example but with an extra step:
<script type="text/javascript">
window.onload = function () {
try {
var movsArray = '#Html.Raw(JsonConvert.SerializeObject(Model))';
var opt = JSON.parse(movsArray);//Extra step
if (opt.length > 0) {
//You can use opt as array of objects
}
} catch (Error) {
console.log("Error");
}
};
</script>
or maybe you can use a loop instead of if
<script type="text/javascript">
window.onload = function () {
try {
var movsArray = '#Html.Raw(JsonConvert.SerializeObject(Model))';
var opt = JSON.parse(movsArray); //Extra step
for(var i = 0;i<opt.length;i++){
//you can use opt[i] as object, example opt[i].id
}
} catch (Error) {
console.log("Error");
}
};
</script>
Where Model is List<Mov_Tipo>
The code I wrote works, but it could be better. I am writing out the same function three times, one for each of the combo box elements. I am stuck on how to make this more efficient. I have looked at creating an object and putting each of the variables in an array, but I was not able to successfully get it working.
var csCategory = <%=csCategoryArray%>,
csKeyword = <%=csKeywordArray%>,
csEntity = <%=csEntityArray%>;
addOption = function (selectbox, text, value) {
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
$(function () {
// Temp test stuff to populate option list
var selectObj = document.getElementById("combobox1")
if (selectObj) {
for (var i=0; i < csCategory.length;++i){
addOption(selectObj, csCategory[i], csCategory[i]);
}
}
});
$(function () {
// Temp test stuff to populate option list
var selectObj = document.getElementById("combobox2")
if (selectObj) {
for (var i=0; i < csKeyword.length;++i){
addOption(selectObj, csKeyword[i], csKeyword[i]);
}
}
});
$(function () {
// Temp test stuff to populate option list
var selectObj = document.getElementById("combobox3")
if (selectObj) {
for (var i=0; i < csEntity.length;++i){
addOption(selectObj, csEntity[i], csEntity[i]);
}
}
});
The obvious first step is to refactor out the shared code. So:
$(function () {
// Temp test stuff to populate option list
var selectObj = document.getElementById("combobox2")
if (selectObj) {
for (var i=0; i < csKeyword.length;++i){
addOption(selectObj, csKeyword[i], csKeyword[i]);
}
}
});
( ... etc ... )
becomes:
function populate(id, collection) {
var selectObj = document.getElementById(id)
if (selectObj) {
for (var i=0; i < collection.length;++i){
addOption(selectObj, collection[i], collection[i]);
}
}
}
$(function () {
populate ("combobox1", csCategory);
populate ("combobox2", csKeyword);
populate ("combobox3", csEntity);
});
I can't see any significant advantage at this stage of putting combobox1 and its siblings into an array, but it may be worthwhile revisiting this code if more comboboxes are added in the future.