I am trying to figure out why my HttpRuntime.Cache collection is always empty when controller action is invoked by $.ajax? In actions invoked normally everything works perfectly and I can get my data from Cache. Maybe actions invoked by AJAX have some different lifecycle and Cache collection is not ready yet? This is my example code:
action:
[HttpPost]
public PartialViewResult SomeAjaxAction()
{
// when receive ajax request HttpRuntime.Cache is always empty, but it shouldn't be
SomeType item = HttpRuntime.Cache.Get("cache_key") as SomeType;
return PartialView("SomeAjaxActionView", item);
}
invocation:
$.ajax({
type: 'POST',
url: '/controller/SomeAjaxAction/',
success: function (response) {
alert(response);
}
});
Is there any way to fix it e.g by custom action filter?
ANSWER
Ok, I found answer here: Access to session when making ajax call to Asp.net MVC action So I imporoved my code with base.HttpRuntime.Cache.Get("key") and it works as expected!
Ok, I found answer here: Access to session when making ajax call to Asp.net MVC action So I imporoved my code with base.HttpRuntime.Cache.Get("key") and it works as expected!
Related
Firstly, thank you for your answers. I have a problem about routing on Asp.Net MVC.
You can see my solution here on the photo where my controllers and views located. I would like to open "UserProfile.cshtml" from "Index.cshtml". Well, my first approach is using Ajax to post "UserProfile Action" in ProfileController.
$.ajax({
url: "/Profile/UserProfile",
type: "POST",
dataType: "json"})
.done(function(response){
window.location = '/Profile/UserProfile'});
this code blocks goes to controller and hits the "UserProfile" Action but returns no error and no view. Even URL doesn't change.
public ActionResult UserProfile()
{
return View ();
}
I would highly appreciate your helpful answers and support. Thank you!
First, you need to have Razor (.cshtml) views, not aspx for mvc to be able to serve these pages out of the box. If you have a controller action named UserProfile in a ProfileController and call return View(), then mvc will be default try to return the view located at Views/Profile/UserProfile.cshtml (it will actually also check a couple other locations such as the Views/Shared/ folder for the view). The following should work for you:
//located in ProfileController
[HttpPost]
public ActionResult UserProfile()
{
return View();
}
//located at Views/Profile/UserProfile.cshtml
`<h4>you've found your user profile page!</h4>`
If you're trying to hit this view by ajax- then you'll need to attack the problem from a slightly different direction. Redirecting on the server side will not work with ajax since it is asynchronous. You can achieve this by using the .done() ajax callback something like the following:
$.ajax({
url: "/Profile/UserProfile",
type: "POST",
dataType: "json"
}).done(function(response){
window.location = '/Profile/UserProfile'
});
I have a View which is the container for a PartialView. Let's say a Customer - Orders relation. The View should received a CustomerViewModel whereas the PartialView a collection of Orders, such as IEnumerable<OrderViewModel>.
I basically have two ways of doing this (not to mention Angular), either Razor or jQuery. With Razor was pretty straightforward by utilizing #Html.Partial("_CustomerOrdersPartial", Model.Orders). But let's assume I cannot use Razor syntax and here it is how I ended up posting this question. I have read many posts on this matter but, most of them (not to mention all), suggest to use $("#container").load('#Url.Action("ActionName", new { parameterX = valueY })). Then here are my questions:
Why to mix Razor and jQuery?
Is this the only way?
Is there any way to call the View and pass the model?
The last question has to do with the fact that the above code requires an action on the server-side to be called, whereas the #Html.Partial("_CustomerOrdersPartial", Model.Orders) mentioned above will just call the View (client-side) and send the given Model in.
Any idea on how to solve this would be really helpful.
Thanks in advance for your time and thoughts.
my solution is:
function ReturnPanel(div, panel) {
$.ajax({
type: "POST",
url: "#Url.Action("GetPanel", "ControllerName")",
data: JSON.stringify({ 'idCurso': idCurso, 'panel': panel }),
contentType: 'application/json; charset=utf-8',
success: function (response) {
$("#" + div).html(response);
},
error: function (xhr, status, errorThrown) {
//Here the status code can be retrieved like;
alert("Error: status = " + xhr.status + " Descripcion =" + xhr.responseText);
}
})
}
in cs.
[HttpPost]
public ActionResult GetPanel(int idCurso, string panel)
{
Contenido contenido = new Contenido();
contenido.IdCurso = idCurso;
return PartialView(panel, contenido);
}
This code should do it. The trick is to acquire the URL and then make sure you get the parameter list right. I used a little Razor to get the URL but you don't have to. Also, If you fail to match the parameter list, your call will not even be acknowledged. You have been warned. I tried to name every thing in a way that helps.
var url = '/controllerName/ActionName';
$('#pnlFillMee').load(url, {NameOfParam: $('#elementID').val() },
function () {CallMeAfterLoadComplete(); });
Here's a real world example I use at work. ReviewInfo is an action in the
controller associated with this page. It returns a partialview result.
$(document).ready(function () {
var url = '/supervisor/reviewinfo';
$('#pnlReviewInfo').load(url, { FCUName: $('#FCU').children(':selected').text(), AccountsFromDate: $('#AccountsFrom').val()}, function () {
InitializeTabs(true);
});
});
This goes somewhere on your form.
<div id="pnlReviewInfo" style="width: 85%"></div>
EDIT:
I would also look up the other jQuery functions like $.get, $.post and $.ajax which are more specialized versions of $.load. and see this link which might answer all your questions about passing models:
Pass Model To Controller using Jquery/Ajax
Hope this helps
wrapping up this question and thanks to #stephen-muecke and #charles-mcintosh for their help:
Using #Html.Partial(partialViewName) the server returns a string resulting from the partial view passed in. Preferred method if you need to manipulate the partial before being displayed. Otherwise, using #Html.RenderPartial(partialViewName) will write into the stream output sent to the browser, the HTML code from the given partial.
As per jQuery API, $(elem).load(url[,data][,complete]) will place the returned HTML into the matching element. Thus, it requires an action method for the given url.
If for whatever reason Razor cannot be used on the UI, chances are you would likely end up either hard-coding the url like in the sample code provided above by #charles-mcintosh or using Angular.
I have a method that follows:
public static void UpdateAll()
{
// Updates database
}
and I have a MVC Application, the view is as follows (removed lines for clarity):
<button id ="btn">Update</button>
//...
<script>
$('#btn').click(function () {
#{
project.models.settings.UpdateAll();
}
});
</script>
The project.models.settings.UpdateAll() method fires as soon as the page loads. Is there a way of making this method load, only once the user has clicked the button?
To test I did replace the method with a simple console.log and that worked as intended.
Any pointers, examples are much appreciated.
Kind regards
I think you're missing a fundamental understanding of how web applications work.
When you put the following into your view you are declaring a chunk of server-side code that will be executed while the view is being processed on the server-side.
#{
project.models.settings.UpdateAll();
}
The reason that it works when you replace it with a console.log is that console.log is client-side code and it executes on the client (i.e. in the browser).
The only way you are going to call server-side code (your UpdateAll method) from client-side code (your button click event handler) is by making an AJAX call.
The simplest thing would be to first expose your UpdateAll method as a controller action. Generally for actions that respond to AJAX calls I like to create a separate controller but that's not absolutely necessary.
public ServiceController : Controller
{
public ActionResult UpdateAll()
{
}
}
Now from your client-side code make an AJAX call to that action.
the way you are doing will not work.
the method will be called when view loads as it is server side code and it will be executed on view rendering time.
so call an action using ajax and in that action call this method:
$('#btn').click(function () {
$.ajax({
type: "GET",
url: '#Url.Action("MyAction","My")',
success: function(data) {
},
error: function(result) {
alert("Error");
}
});
});
write an action in controller:
public void MyAction()
{
project.models.settings.UpdateAll();
}
Initially, my controller action accepts GET. When my data grew, I was forced to move to POST method to be able to send larger data.
My controller action is as follows:
[HttpPost]
public ActionResult ClausesPdf(MyArrayModel obj)
{
...
return File(pdf, "application/pdf", "file.pdf");
}
How can I call this action and download the file using javascript?
Update: I realized that my original answer about AJAX was not entirely accurate since there is no way to return a file from an AJAX call. I suggest that you look at this SO question: Download Excel file via AJAX MVC. I believe #CSL has a good answer that is similar to what you want.
My answer is not plain javascript. This is an AJAX call in jQuery on how it could be done there:
$.ajax({
url: urlControllerAction,
type: 'POST',
cache: false,
data: //your parameter data here
})
.done(
function(result, textStatus, jqXHR) {
//do something with the "result"
}
)
.fail(
//what should be done if something goes wrong
);
I'm using MVC3 - i have a javascript function that uses jQuery get() to get a PartialView from a controller.
The problem is that it's being cached and i keep getting stale content back.
I've tried [OutputCache(Duration=0)] on the action, thinking it would prevent it caching, but no joy. Could it be the client caching it too?
EDIT:
I've recently been using another way to prevent caching which may be useful to some.
$.get("/someurl?_="+$.now(),function(data) {
// process data
});
It's obviously not as clean, but because each request passes a _=12345678 (timestamp) it's never cached.
Hope it helps.
GET requests could be automatically cached by the browser so you could use the .ajax() function which contrary to the .get() function allows you to disabled caching:
$.ajax({
url: '/foo',
type: 'GET',
cache: 'false',
success: function(result) {
}
});
Another possibility is to use POST:
$.post('/foo', function(result) {
});
IE is particularly bad about that. You can disable all AJAX caching with the following:
$.ajaxSetup({
cache: false
});
It seems by default that all MVC 3 partial views are automatically cached, but you can control this from the controllers for each partial view that is returned with an attribute (or annotations as they are called in Java) in front of the action:
[OutputCache(Duration = 0)]
public ActionResult PersonEdit(string id)
{
// do query and fill editvm here
return PartialView("PersonEdit",editvm);
}
So the duration is set to zero. There are probably many other attributes that can be set to turn off caching, but so far this seems to work for me on an individual basis.
thanks to both of you, the first one still cached with type="GET" even with cache:'false' specified. That's using chrome and local IIS7.
I ended up with
$.ajax({
url: '#Url.Action("GetMyPartialView","MyController")/' + parameterId,
type: 'POST',
cache: 'false',
success: function (result) {
$('#dynamicContentDiv').html(result);
}
});
Works fine, thanks for you responses.