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)]
Related
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.
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 call a method in a separate Class file that needs to update a label.
[WebMethod] //needed for the AJAX call
public static void MyClick(int postid, int userid) //must be static
{
Page page = new Page();
//Page page = HttpContext.Current.Handler as Page //Pass the Page but don't work
MyClass.MyMethod(postid, userid, page);
}
The method MyClick() is called from an asp.aspx file (With MasterPage), to a separate MyClass.cs file.
I am not being able to get the Control (Label) with FindControl(). My guess is the "Page" is not being passed correctly. For what i've seen in debug, "page" comes with many exceptions.
((Label)page.FindControl("ContentPlaceHolder1_lbl)).Text = "foo";
This is the sequence:
1) User clicks sort of a "Like" dynamically-created LinkButton
2) There is a JS listener that on click changes to "Dislike" (example) and does an AJAX POST to aspx page method MyClick() with parameters (postid, userid).
3) MyClick() calls MyMethod(postid, userid) that is in MyClass.cs
4) MyMethod() does some SQL (was working) and updates the label (AJAX call not working since MyMethod() tries to set label to "foo").
You're not passing the current page, you're creating a new one:
Page page = new Page();
You could just pass a reference to the current page:
MyClass.MyMethod(postid, userid, this);
(Though in order to do that your page method shouldn't be static. In fact, in order to reference anything on the page instance that method shouldn't be static. See edit below)
However, in general it's best practice not to have other components rely on your page elements. Only the page's code should know/care about the UI elements it owns.
Instead of having the method set the value, have the method compute and return the value and then have the page set it. Something like this:
var result = MyClass.MyMethod(postid, userid);
myLabel.Text = result;
That way the external component isn't tightly coupled to this specific page, can be re-used by other pages, etc.
Edit: What you're trying to do physically won't work in the framework you're using. AJAX-invoked web methods are static for a reason. They don't maintain page state. So in the context of that web method there is no page and there is no label. The AJAX call is a simple service which accepts values and returns a response.
So even if you could update a label server-side, that's not going to do anything client-side. Your client-side code needs to update the markup in the browser. To do that, the AJAX call should simply respond with the new value and the JavaScript code should use that returned value to update the page. Something like this:
[WebMethod]
public static string MyClick(int postid, int userid)
{
return MyClass.MyMethod(postid, userid);
}
As in the earlier part of this answer, that external component should simply calculate and respond with the new value. It should not be coupled to the page. This web method should result in the client-side code receiving the updated value. Then, however you manage that client-side (you have no client-side code in the question), you would update the page markup with that resulting value.
So I've always used the loose PRG pattern where you return a view on ModelState validation failure from a POST action. However, it's always bothered me that I have to build the model not only in the GET action, but also rebuild it again in the POST action on failure. I've used different methods of doing the rebuilding using "view model builders" or just a private function within the controller that builds the view model for both actions, but these still bother me as well.
After reading this article by Ben Foster (http://benfoster.io/blog/automatic-modelstate-validation-in-aspnet-mvc), it makes a lot more sense to just rely on the GET action to build your view model - keeping it one area of the code - and then use the necessary action filters to save the ModelState for rendering when you are redirected back to GET on a failed POST.
So I've implemented that using the filters Ben mentions in his article like below. However, I am curious what happens if the user refreshes after they have been redirected back to the GET on a ModelState failure? How would I differentiate between someone accessing the GET directly versus a ModelState failure? Currently the ModelState would be gone if a user refreshes at that point. Is that the correct action, or should the user continue to see the errors until they POST with valid data? Essentially, should they be seeing the data that is in the database, or should they continue to see the changes they made when POSTing?
[ImportModelStateFromTempData]
public ActionResult Edit(int id)
{
// in a real application this would be retrieved from the db
var editView = new EditView()
{
UserId = id,
Name = "John Doe",
Age = 20,
Message = "Hello world"
};
return View(editView);
}
[HttpPost]
[ValidateModelState]
public ActionResult Edit(EditCommand editCommand)
{
// save to db here in real application
return RedirectToAction("Success");
}
I use the same [ImportModelStateFromTempData] filter in a couple projects, and it works great.
In my opinion, if the user refreshes, you shouldn't preserve any model state errors. The user is asking for a fresh view of that page, and it'd be frustrating to never be able to get a clean view. In same vain that refreshing after a POST shouldn't resubmit a form, refreshing after a GET shouldn't preserve a POST.