Caching data in ASP.net MVC - c#

A friend asked me to use Output Cache to cache data, that works good, but the thing is that I want to get data from the database and then interact with that data, I mean, I want to grab a huge data from the database, and then get only some data from that huge data according to the user activity dynamically.
[OutputCache(Duration =600, VaryByParam ="none")]
public ActionResult GetData()
{
var result = context.People.ToList();
return View(result);
}
That's an example, but let's say that I want to use pagination for that data in my view, and I want to show every person according to the date birth, for example default page current week, with a link called 'Next' and other one called 'Previous' . When 'Next' link is clicked I want to display only the people which birthday is the next week, same thing with 'Previous', showing just people with birthday on the previous week..
But using Output Cache I'm displaying the same data all the time... Is it possible to do this interacting with the database only the first time, caching that data, and then interacting with that data and not read against the database again during the time I set on the duration?? Do you advise me to use another Caching Tool different than Output Cache?

Instead of caching the entire view, maybe you could just add the result to the session state?
public ActionResult GetData()
{
if (HttpContext.Current.Session["peopleList"] != null)
{
return View((List<People>)HttpContext.Current.Session["peopleList"]);
}
else
{
var result = context.People.ToList();
HttpContext.Current.Session["peopleList"] = result;
return View(result);
}
}
You can control how long session state lasts in your Web.config or through IIS.

Related

How do I show a loading screen/icon while loading a view that requires querying a database? Asp.Net Core C#

Currently I have a view that has just a single form with three values. When a user submits the form with those three values, my controller checks if all three values actually have a value other than being empty, and if they do then it calls my service that fetches data.
public IActionResult Index(string clientName = "", string tableName = "", string date = "")
{
if (!string.IsNullOrEmpty(clientName) && !string.IsNullOrEmpty(tableName) && !string.IsNullOrEmpty(date))
{
// Unimportant stuff for setting temp variables for FetchData parameters removed
TheData = _fieldDataService.FetchData(tempAcr, tempID, tableName, date, numRows);
}
return View(TheData);
}
My goal is to make the view display a loading icon or something while the data is being fetched. I've looked into JQuery and Ajax but I have no experience with either and cannot figure out how to apply them to my specific task. Since I am using Asp.Net Core, I also looked into using Blazor, but I couldn't wrap my head around it either.
Could somebody point me in the right direction as to what I should/could use to solve this problem? I have a vague understanding that there needs to be some sort of asynchronous function that retrieves the data, but nothing more than that.
You need to fetch the data with JavaScript and manipulate the UI to show a loader. But anyway, a request like this should be so fast, that you don't even need a loader.
I'm also a bit worried that you are passing a tableName as input parameter. You aren't just string concatenating the query right? You might be susceptible to SQL injections, see https://en.wikipedia.org/wiki/SQL_injection.
To do a request with JavaScript, look into the XMLHttpRequest, see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest, or the new way of doing it with fetch(...), see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
This answer shows a more practical example: Display loading image while ajax fetches file content.

How can I hold data through multiple Web pages

Starting at WebPage1, the user enters some data into a textbox and performs a search based on that search data. Then the user navigates away from WebPage1 to WebPage2 via a link.
How can I maintain their original search data when the user returns to WebPage1?
The user does not want to see the data in a query string. However the data is not sensitive, and any data from the client will be handled before processing.
We are using C# Mvc framework with Razor.
I have been trying to Post the entire model each time rather than using Get requests. However, this is not working well and does not follow a simple Post-Redirect-Get pattern more like Post-Redirect-Post.
You can use sessions to pass data from one webpage to another until you close the browser here is an example
//assuming the method below will return list of Products
var products=Db.GetProducts();
//Store the products to a session
Session["products"]=products;
//To get what you have stored to a session
var products=Session["products"] as List<Product>;
//to clear the session value
Session["products"]=null;

Access some session details in MVC view

I have a session in my Login Controller and there i send List of details via Session to the another page.So i need to take one item of the list to show in mvc view(Actially i need to show UserName in my mvc view).
My Controller
public ActionResult Login(User usrdtl, string returnUrl)
{
//some code here
List<UserDtl> usrList = newsManager.GetUserdetailsByuId(usrdtl.uId);
System.Web.HttpContext.Current.Session["UsrSession"] = usrList ;
}
This usrList consist of lots of user details,i need to show UserName in my view.
In my view i tries to take it as,
<span>#Session["UsrSession"] </span>
But it shows me error
System.Collections.Generic.List`1[NTL.Sys.Entities.UserDtl]
How can i get this ?
It actually does not show you error. It shows the object representation by calling .ToString() on the object.
In your case, Session["UsrSession"].ToString() returns System.Collections.Generic.List1[NTL.Sys.Entities.UserDtl].
Your code actually has no problem at all, modify it to show exactly what you want to show.
I assume that the list contains exactly 1 item. To show the UserName, try:
<span>#((Session["UsrSession"] as List<UserDtl>).First().UserName) </span>
How to show the list is up to you, if you want to display a list of Users, just loop through it. The above code is just an example.

Editing data from database in razor view

I'm writing code in ASP.NET but it's not a language related question. Every time when I write a web application and I display some data from database using razor view I have this problem. For example I have simple table with Id and Name in my database. I want to display a table with Names using EditorFor fields. User can edit all the data and save it. So I use row Id as EditorFor Id, read input values in javascript method, use WebMethod to pass them to Controller and save changes to database. But in this case I can change EditorFor Id in Firebug and pass changes with wrong ids. What's the way to edit data in that case? I don't want to click edit link and redirect user to edit page when he can edit one row. I have 5 rows in database with Names and I want to edit all of them at once.
That's some kind of security, and you must add security method in this situation.
One way is to use RBAC method for your security structure. For example:
Create a table and name it user_groups, then create table of users that has and foreign key to user_groups
Then also add the foreign key to your " simple table "(that has id and name) to user_groups, that represent witch user_groups can update the row,
I this that's clear. When someone want to edit a row, you check if that user has permission to change the row or not?
You can search term "Role Base Access Control" in asp mvc,
Also something useful here:
http://www.webdevbros.net/2009/12/16/role-based-access-control-in-asp-net-mvc/
[HttpPost]
public ActionResult EditEmailTemplate(EmailTemplate_Mst emailTemplate_Mst, string Command, int id = 0)
{
try
{
EmailTemplate_Mst et = _repository.GetEmailById(id);
if (Command == "Update")
{
et.Title = emailTemplate_Mst.Title;
et.EmailTemplate_Content = emailTemplate_Mst.EmailTemplate_Content;
et.EmailTemplate_LastModifyBy = Convert.ToInt64(Session["UserId"].ToString());
et.EmailTemplate_LastModifyDate = DateTime.Now;
_repository.UpdateEmail(et);
return RedirectToAction("ViewEmailTemplate");
}
}
catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(new { id = emailTemplate_Mst.EmailTemplate_Id });
}
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-insert-update-and-delete-application-in-mvc-4-using/

How to add temporary data using a wizard?

I am using a Wizard control to capture users vehicles they own.
Stage 1 - Captures users name, address etc
Stage 2 - Captures only one vehicle (one vehicle consists of reg, model, mileage and manufacturer)
Stage 3 - Gives a summary of the details entered and saves the record when they click finish.
I would now like to capture multiple vehicles at stage 2.
Since the record is saved at stage 3 my guess is i need someway of storing each vehicle at stage 2 (which the user can view and edit if required before saving the record) and then passing all temporarily saved vehicles to my method at stage 3 to save it against the user.
How could i approach this? My concern with my research is that most of the methods available dont show how to store each vehicle temporarily?
You can use the Session variable to store the value if you are using the web application otherwise cache is also useful container. If your wizard is single page with multiple form you can also use the hidden field or viewState. Have a class with all the properties you want to store and use the class to put in the Session
public class MyData
{
public string Name;
public string Address;
}
In the first part of wizard do like this then once value is populated store in the Session before moving to next page. In next page so like this
MyData myData = (MyData]Session["myData"];
//again update rest of the data from current page and
Session["myData"] = myData;
//Go to next page

Categories

Resources