I have an application in ASP.NET MVC with a simple form which reads data from a file and shows the data in the form in browser.The issue is that every time I refresh the browser,the data from the file is added again in the front end.This is the controller where I have the issue:
public ActionResult Main(BankingModel _bm)
{
ViewBag.List = IO.Read();
return View(_bm);
}
IO.Read reads the data from the file,stores it in the Viewbag and send it to the view.But the controller is called every time I refresh the page and the data from the browser remains,resulting in duplicated values.Is there a way,when I refresh thee browser,to also refresh the front end view data from the form?
Regarding your particular case, you were not intiailzing a new instance of your List<BankingModel> which caused the data to be appended to the list always. The solution to this would be to initialize a new instance of your list inside the Read method:
public static List<BankingModel> lst = new List<BankingModel>()
And in order to clear your ViewBag since ViewBag maintains data on refresh, you can just call ViewData.Clear(); in your Controller method since ViewBag uses it internally.
Related
This is an ASP.NET MVC project. I'm trying to retrieve value from a session and it always returns null.
The SaveToSession & GetFromSession methods are in a separate helper class.
When the submit button is clicked, it makes a call to the controller method and in turn to the helper method to save data in session.
Another anchor tag click (which has the controller path) will hit the same controller which calls the helper method to fetch the data from session. This is where the data is null always.
These are the methods in my helper class
public static void SaveDataInSession(string sessionName, IEnumerable<Item> lstData)
{
System.Web.HttpContext.Current.Session[sessionName] = lstData;
}
public static void GetDataFromSession(string sessionName, out IEnumerable<Item> lstData)
{
lstData = null;
var test = System.Web.HttpContext.Current.Session; //This session has a new SessionID and hence does not have the data.
if (System.Web.HttpContext.Current.Session[sessionName] != null)
{
// it never comes into this block
}
}
During debug, I can see that the data is saved into the session as I can see the session name in the keys list.
The same code worked fine in another ASP.NET MVC project. I checked the web.config file of that project if there were any session related entries and there were none.
UPDATE: I have observed that, when saving the data the session id generated is different and when fetching the data, it has another id. I think this could be the reason, but why is it creating new session Ids when I'm not even refreshing the page. What can be done to fix this.
The System.Web.Mvc version is 5.2.3.0
I have an Action method like below..
[HttpGet, Route("All-Users"), OutputCache(Duration = 86400)]
public async Task<ActionResult> AllUsers()
{
var list = await _user.GetUsersList();
return View(list);
}
I have another Action method that saves the User.
Here the problem is that when I save the user..it still shows cache Page content. So this means newly added users are not appearing.
Kindly suggest how can i get rid of this issue.
I checked on Google that Cache can cleared as shown in this page
Question: Will it clear cache for all pages or for above action method
only ?
I have a scenario where in I am using the Session to store an object in one controller action and trying to retrieve it another controller action. Both the actions are triggered from the same view and reside on the same controller. Unfortunately, I am not able to retrieve the session variable in the second controller. The session Id remains the same and I am ensuring that the object was written into the session in the first action. The session data, however, disappears when the view is returned in the first action.
Here is my Controller code flow -
public PartialviewResult DoSearch(string paramCustId)
{
//invoking a method to perform a search task. I am also passing the controller session as a parameter
//this function is called in a separate thread and the main thread does not wait for it to complete before returning the view
multiSearch(paramCustId, Session);
}
return PartialView("_partialView1");
public void multiSearch(string searchParam, HttpSessionStateBase controllerSession)
{
//code to retrieve response from backend into the variable tempSearchSet
controllerSession["searchResult"] = tempSearchSet;
//verified that tempSearchSet is stored in Session under the key "searchResult" and Session.Count is 1.
}
//Another controller action that is triggered from the same view after a certain delay to fetch the data in session
public PartialViewResult PollSearchResults()
{
var tempSearchResult = Session["searchResult"] as List<SearchResultSet>;
//This is where i do not see data in the session. I have verified that the multiSearch method is complete and has updated the data in the session.
//here Session.SessionID is the same as above, but Session.Count is 0
}
Is there a different way to handle Session in mvc or am i missing something elementary here? Also, is there a better approach to manage this caching scenario?
Found the solution. I had to initialize the session variable in the Session_Start method of Global.asax.cs. This one line made it work for me.
HttpContext.Current.Session.Add("searchResult", new List<SearchResultSet>());
I am still unclear why this line is needed as the session variable get and set worked in the first action method without the initialization. Guess i'll keep that for future research.
Suppose I were to have a web application and a view called innerPage for the application who's model looks something like this:
public class innerPageModel
{
public bool isFirstTime = true;
public List<int> threadIDList;
}
And here is the controller for my innerPage:
public ActionResult innerPage(InnerPageModel model)
{
if (model.isFirstTime == true)
{
Thread t = new Thread(Work);
model.threadIDList.Add(t.ManagedThreadID);
model.isFirstTime = false);
}
System.Diagnostics.Debug.Write((model.threadIDList.Count).toString());
}
Now my innerPage view is being refreshed every 5 seconds and therefore traversing my innerPage controller each time. The problem is that all of the data in my model is being reset after every time I traverse the controller (Everytime it goes inside the if-block, indicating that model.isFirstTime is being reset to true when I only want to traverse that if-block on the first time). Likewise, my model.threadIDList is being reset everytime through.
Is there a way for me to save the data in my model such that it isn't lost everytime my view refreshes?
The MVC model assumes the controller will be invoked, return an ActionResult and then be done.
It does not seem safe to kick off threads in the controller action.
If you need data to remain between HTTP requests, you can store it in the Session or in Cache, depending on whether the data is per-user or global to the website.
If you need true background processing, look at
WebBackgrounder
Quartz.NET
FluentScheduler
I am currently in the process of creating an MVC application, it's basically just a big CRUD-tool for database contents.
For the small tables that are used to limit some choices (countries, categories, things like that) I have created 1 page that loads the requested table and allows the user to add/delete/edit the properties using only Ajax calls.
When the page is loaded, the user gets a dropdownlist with all tablenames. When submitted, the following code is triggered:
public PartialViewResult OpenConfig(string SelectID)
{
using (DBconnection db = new DBconnection())
{
switch (SelectID)
{
case "---":
return null;
case "1":
var countries = (from x in db.tbl_CountriesSet select x).ToList();
return PartialView("Countries", countries);
case "2":
var supplierstatus = (from x in db.tbl_SupplierStatusSet select x).ToList();
return PartialView("Supplierstatus", supplierstatus);
case "3": .....
}
}
}
Here's where it gets interesting. Suppose I open the Countries window, it loads correctly, I am able to add/edit/delete a country. These entries are updated on the page using jQuery, and concurrently an Ajax call is used to updated the database. Both of these work fine, both the database is updated and the page. I can keep working and all changes are reflected in both the page and the db, the issues starts when reloading the partial view.
When I select the Countries value in the dropdownlist and submit it again, the program just skips the method shown above and displays the same partial view it showed me when I first requested the list.
I set a breakpoint in the method, if I load something I haven't loaded before it gets triggered, but not for pages I already requested.
In Firefox, this works and the partial view is updated (and the breakpoint is triggered), but in Internet Explorer, my controller is completely ignored ans it keeps displaying the same page (even when I go to a completely different page and then go back to the settings page).
Can anyone tell me how I can tell IE to explicitly reload the partial view containing the current database contents?
It's browser caching works. It returns you cached results.
Use adding current date value to url to allow loading new results from web server:
$('#container').load("http://mysite/myview/?" + new Date().getTime(), function () { });
On top of your controller functions, try:
[OutputCache(Duration = 0)]