Pre loader for index action MVC - asp.net-mvc

Im trying to do a preloader for a page
the index action controller:
myapp/FR/Index
public ActionResult Index(){
return View(db.SP_GetRegistrosFRByID(0).ToList());}
the view, there isnt a begin form because is a get request:
#foreach (var item in Model)
{
...etc...<tr>
<td>
#Html.DisplayFor(modelItem => item.CodIden)
</td>
<td>
#Html.DisplayFor(modelItem => item.Nombres)
</td> ...etc

As David says it's a broad and open-ended question and you can apply lot of approaches. You have not given details about how index gets called (form submit, button click ..)
First you need a div with the loader image in the view where you need the preloader to display.
<div id="loader" class="loader">
Working.. <img src="~/Images/loading_small.gif" />
</div>
and now the JS function that shows/hides the div with the loader image based on your data loading status.
function pageLoading(status) {
if (status == 'true') {
$("#loader").css('display', 'block');
}
else {
$("#loader").css('display', 'none');
}
}
Before making the AJAX request you can call pageLoading("true"); to start displaying the image and finally when the table data gets populated call pageLoading("false"); to hide the loading image. Something like
$.ajax({
url: 'your index method url',
success: function (partial) {
$('#results').html(partial);
pageLoading("false");
}
error: function () {
pageLoading("false");
}
});

Related

how to disabled asp-action link after one click

i would like to disabled asp=action link after one click
i have a foreach loop to display my book in table in my view
my asp-action for add book in the cart is in the loop but i want to disabled just the book who already in the cart not all books
<a asp-action="AcheterLivre" asp-Controller="Achat" asp-route-id="#item.Isbn" id="disabled" onclick="return myFunction(this);"> Ajouter
i try something with jquery but its dont work well
i tried this
<script>
function myFunction() {
$("#disabled").one("click", function () {
alert("this book is already in the cart");
});
}
i have this function in my class
its verify if the books is in the cart maybe i should use it ?
public bool IsPresent(string isbn)
{
//rechercher si l'isbn correspond a un livre de la liste
AchatLivreViewModel livre = ListeElements.Find(element => element.Isbn == isbn);
if (livre != null)
{
return true;
}
else
{
return false;
}
}
Why not trying this simple approach:
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Isbn
</td>
<td>
#item.Titre
</td>
<td>
<label class="btn btn-primary" style="padding:0">Add to Cart</label>
</td>
<td>
<label class="btn btn-danger" style="padding:0">Remove From Cart</label>
</td>
</tr>
}
</tbody>
And in your javascript, if you don't want to use Ajax, you can manage your cart items all on client side using an array of objects, Let's name it CartItems:
var CartItems = [];
$('.ADD2CART').click(function () {
if ($(this).closest('tr').hasClass("ExistingInCart")) {
alert('Already in Cart !!');
}
else {
// add this item to the Cart through Ajax or
// local javascript object: e.g.:
CartItems.push({
ISBN: $(this).closest('tr').find('td:eq(0)').text().trim(),
Title: $(this).closest('tr').find('td:eq(1)').text().trim(),
});
$(this).closest('tr').addClass("ExistingInCart");
}
return false; //to prevent <a> from navigating to another address
});
$('.RemoveFromCART').click(function () {
$(this).closest('tr').removeClass("ExistingInCart");
var isbn = $(this).closest('tr').find('td:eq(0)').text().trim();
CartItems = CartItems.filter(x => x.ISBN !== isbn);
return false;
});
Once you need to submit or post the page, you have all the already selected books in CartItems array.
To add this javascript code to your view, choose one of the options:
Put this block at the bottom of your view and copy the above script inside the <script></script> tag:
#section scripts{
<script>
.... copy it here ...
</script>
}
copy the script code inside a newFile.js and add it to your view
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/newFile.js"></script>
You may decide to bundle this newFile.js
try this:
Ajouter
And your Javascript:
function foo(input) {
if ($(input).attr('yetClickable') === '1') {
$(input).attr('yetClickable', '0');
return true;
}
else {
// this false returning will counteract the effect of click event on the anchor tag
return false;
}
}
Once an Item is removed from the cart, again you need javascript to select that Item by its Id and change the yetClickable attribute back to 1 (in order to be clickable).
Note: This idea above (upon your scenario) works until the page is not reloaded. Otherwise, you need to handle ADD/Remove operations on the Cart through Ajax.
Hope this helps.

Track user clicks from list populated of URL's using MVC framework

I have an MVC 5 application that displays a list of 100+ unique URL's. The user can sort, search, and eventually click the URL from the list launching the website in a new window. I want to be able to track every time someone clicks a URL from that list. The URL list is populating as expected. View code below:
<table class="table table-condensed table-hover table-responsive table-striped">
<tr>
<th class="col-md-1">
#Html.ActionLink(" Name", "Index", new { sortOrder = ViewBag.ReportNameSortParam, SelectedReportCategory = ViewBag.SelectedReportCategory, FindReportName = ViewBag.FindReportName}, new { #class = "glyphicon glyphicon-sort", #title = "sort by name" })
</th>
</tr>
#foreach (var item in Model)
{
if (ViewBag.counter == "")
{
ViewBag.rowType = "normalRow";
ViewBag.counter = "1";
}
else {
ViewBag.rowType = "alternateRow";
ViewBag.counter = "";
}
<tr class=#ViewBag.rowType>
<td class="col-md-1" title="#Html.DisplayFor(modelItem => item.Report_Description) : #Html.DisplayFor(modelItem => item.SLA)">
#Html.DisplayFor(modelItem => item.Report_Name)
</td>
</tr>
}
</table>
What would be the best approach to track a user click when they are doing this via the View? I have a column in my table called 'Hits' that I would like to increment by 1 whenever that URL gets clicked. Ideally, after a user clicks a URL, I would like for the list to stay where it is and not have to refresh by hitting another controller and then repopulating. How can I write to the database on via the View?
as mentioned... capture the click event of each link clicked and perform an Ajax post to the relevant controller and action.
$(document).ready(function () {
$(document).on('click', 'a', function () {
var linkID = $(this).attr("id");
$.ajax({
type: "POST",
url: "#Url.Action("YourAction", "YourController")",
data:
{
linkid: linkID
}
});
});
});
hope that helps.
Consider standing up an action method that receives the URL and redirects to the final destination:
#Html.DisplayFor(modelItem => item.Report_Name)
In the controller, add:
public ActionResult Redirect(int id, string url)
{
//Get record using ID, and update Hits column
//Redirect to the final URL
return Redirect(url);
}
Be aware that if your URL's use any special characters, some encoding may occur... that might mean you have to do some encoding on the client end potentially. It's just good to test that out to confirm.

Why partial view not rendering in the same page? (ASP.NET MVC 4)

I've faced a problem for partial view displaying.
//This is Controller Action
//_AcademicInfo is the Partial view name
public PartialViewResult GetAcademicInfo(int empId)
{
var acad = _academicService.GetAcademinByEmp(empId);
return PartialView("_AcademicInfo", acad);
}
<!--Parent/caller page cshtml code-->
#Ajax.ActionLink(
"Academic Details",
"GetAcademicInfo",
"Employee", new {empId = Model.Id},
new AjaxOptions {UpdateTargetId = "AcademicDetails", InsertionMode = InsertionMode.InsertAfter}
)
<!--This is partial view cshtml-->
#model IEnumerable<Hik.PhoneBook.Data.Entities.Academic>
<div id="result">
<table>
<tr>
<th>Degree Name</th>
<th>Passing Year</th>
<th>CGPA</th>
<th>Institute</th>
</tr>
#foreach (var acad in Model)
{
<tr>
<td>#Html.DisplayFor(m => acad.DegreeName)</td>
<td>#Html.DisplayFor(m => acad.PassingYear)</td>
<td>#Html.DisplayFor(m => acad.CGPA)</td>
<td>#Html.DisplayFor(m => acad.Institute)</td>
</tr>
}
</table>
</div>
As because, I need to get the partial view by a Link clicking, not by rendering directly like #Html.Partial("_AcademicInfo", Model.Academic). Thats why I've used Ajax.ActionLink. Whenever I click on "Academic Details" link, its executing the accurate result. But unfortunately its not displaying in the same page. Its going to appear in another page. (Its MVC 4)
What should I need to change to render the partial view in the same page?
If you are redirecting to a new page rather than staying on the same page, it means that jquery.unobtrusive-ajax.js is not loaded and #Ajax.ActionLink() falls back to a normal link.
Either you have either
not included the script
have the scripts in the wrong order (jquery{version}.js must come
first)
You have duplicate scripts
Maybe you can use jquery's .load() function ? Like this.
$("divId").load('#url.action("getacademicInfo")', {empId : 4});
https://api.jquery.com/load/
Try using JQuery Ajax to load the partial view into the Div on the page on button/link click instead.
var jsondata = { Id: iddata };
$.ajax({
url: "/Controllername/GetAcademicInfo",
method: "POST",
dataType: "html",
data: jsondata,
success: function (response) {
$("#divId").html(response);
}
});
Please note that this is just a sample code for giving you an idea.
Hope that helps!

How can I use input in grid view?

I'm going to use a grid view. it contains a check box per row.
its for deleting row. for example when user checked some checkbooks and click on delete button checked rows have to delete.
Now How can I give checked rows ID's in my action ?
Do you have any ideas ?
Thanks.
OK. We assume that you want to retrieve a list of products and show them in a raw html grid.
First of all, arrange your view like this:
#model IEnumerable<MyPrj.Product>
// ... Other codes ...
<table id="tblGrid">
<tr>
<th>Delete</th>
<th>ProductName</th>
// ... Other Properties ...
</tr>
#foreach(var item in Model)
{
<tr id="tr#(item.ProductID)">
<td>
#Html.Raw("<input type='checkbox' id='chk#(item.ProductID)' onclick='chkChange(#chkID)' />");
</td>
<td>#item.ProductName</td>
// ... Other Properties ...
</tr>
}
</table>
<input type="button" id="btnDelete" value="Delete Selected Rows" onclick="performDelete()"/>
Now, you have your view and it will render the grid for you with the supplied model. Then, you need to add some javascript and jquery codes to perform the row deletion for you.
A function to handle checkbox clicks:
<script>
function chkChange(id) {
if ($(id).val() != 'false')
$(id).val('false');
else
$(id).val('true');
}
// ...
</script>
And finally, a function to handle delete button clicks:
function performDelete() {
var rows = $("input:checked");
rows.each(function () {
$(this).parent().parent().remove();
});
}
That's it! - you're done. The complete <script> blog is like the following:
<script>
function chkChange(id) {
if ($(id).val() != 'false')
$(id).val('false');
else
$(id).val('true');
}
function performDelete() {
var rows = $("input:checked");
rows.each(function () {
$(this).parent().parent().remove();
});
}
</script>
You could place the grid along with its checkboxes inside an HTML form and make the Delete button as submit button for this form. Then when the button is clicked, the form will be submitted and the values of the selected checkboxes will be sent to the controller action so that you could delete the corresponding records.

Refresh User Control in MVC

I have 3 user controls in an aspx page in my MVC application.
i bind data from DB from one controller.
on the selection of "Filter / Status" i want to bind data (refresh) to "List" user control with out refreshing "Filter & Status" user controls.
below are my user controls in aspx page.
please help me how to refresh part of the page/user control.
i have tried by returning only "ListView" View data. but its searching for the other 2 views & throwing exception.
<td>
<%Html.RenderPartial("Filter", ViewData["FilterView"]); %>
</td>
<td valign="top" width="15%">
<%Html.RenderPartial("Status", this.ViewData["StatusView"]); %>
</td>
<td valign="top" width="85%">
<%Html.RenderPartial("List", this.ViewData["ListingView"]); %>
</td>
do sth like this
html (aspx page):
<div id="ListingView">
<%Html.RenderPartial("List", this.ViewData["ListingView"]); %>
</div>
...
<input type="button" id="refreshListingView" />
javascript to handle it:
$('#refreshListingView').click(function () {
var selectedStatusId = 'get here proper status id';
$.ajax({
url: '/YourController/GetListingView',
type: "GET",
data: { "statusId": selectedStatusId },
success: function (response) {
$('#ListingView').html(response);
}
});
});
YourController:
[HttpGet]
public ActionResult GetListingView(int statusId)
{
ViewData["ListingView"] = your data filtered by statusId or what you want;
return PartialView("List",ViewData["ListingView"]);
}
Instead of ViewData["ListingView"] I would use dedicated model, but it's just an example. It should work.

Resources