Here's my scenario. I'm calling a url which points to a controller method that returns a partial view:
Controller method:
public ActionResult UserProfile() { return View("UserProfile"); }
Ajax request to get the view:
$.get('/Home/UserProfile', function (data) { $('.content').html(data); });
I would like to cache my "UserProfile" view so that each time the user clicks it, it doesn't have to go back to the server to fetch the view from the controller again.
I would also like to be able to determine if the view's been cached on the client before fetching it from the server, and if it has, get it out of cache and simply inject it into a div on my layout.
Has anyone done anything like this?
You could use the [OutputCache] attribute. It allows you to specify the duration for which you want the view to be cached as well as the location of the cache. For example let's suppose that you wanted to cache the results of the controller action for 30 seconds on the client browser:
[OutputCache(Duration = 30, Location = OutputCacheLocation.Client)]
public ActionResult UserProfile()
{
return PartialView();
}
Now you could trigger many AJAX requests but only one in 30 seconds will be sent to the server:
window.setInterval(function () {
$.get('/Home/UserProfile', function (data) {
$('.content').html(data);
});
}, 4000);
Related
Whenever there is a call to Controller inside View, I want the Controller to return some variables to the View and do not refresh the View.
Already know:
return view("webpage" , compact('variable1', 'variable2') );
What I expect to achieve:
return compact('variable1', 'variable2');
This will not return the Webpage but only some of the variables.
Edit:
Thinking it from a complete different perspective, The question maybe rephrased as such
Is there a way to manipulate REQUEST variables of a web page from the controller? This way, i would be able to get new variables from the Controller without the web page being Refreshed.
With out much to work with, here is an example:
Ajax call:
$.ajax({
url: '/your/route/',
type: 'GET',
data: {getVariable: formInputValue},
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log('Failed');
});
Controller Function:
public function getVariable(Request $request){
$resault = $request->getVariable;
return response()->json($results);
}
Update: as per comments on this answer try this and see if it works for you.
In your controller where you fetch records instead of using a ->get();
change it to paginate(5); this will return 5 records per page. and on your view at the bottom of your </table> add {{ $variable->links() }}
I have an ASP.net MVC project and depending on the filter options chosen by the user I am sending different ajax requests to the same actionresult, for example:
$(document).on("click", "#filter_reset_button", function () {
var url = "/Admin/Index";
ajaxRequest({
url: url,
type: "get",
data: { reset: true },
successCallback: function () {
window.location.href = url;
}
});
});
Other listeners sent different data, something like:
data: { page: 2, filterUpdate: true }
and so on. The Index ActionResult returns different lists of items, depending on different options chosen in the data and the code works completely fine.
A colleage of mine told me, that my code is actually sending two get requests to the AR everytime, so its not efficient. Is that true? And if its the case, how can I refactor it. to make it just one request? If I let window.location.href = url part out, the site actually doesnt load the server response.
Yes you are doing 2 request in button click. First in Ajax Get, Second in Success Call Back.
But Why are you calling window.location.href = url; success call back. ?
If you want update the page after click, you can do partial updates to page. Check this post.
That is correct 2 request called.
First request when you call AJAX get to Action Index in Admin Controller.
Second request when you set window.location.href = url, it will same as you enter /Admin/Index in browser.
In this case you only need window.location.href = '/admin/index?reset=true' in click function
You can see the post here at this post
Actually on success callback you must change your code accordingly to the above post
This is my stack : Ember.js + Express/Node.js
Say i have an Endpoint as \posts, it will return an array of objects.
and i have following template named allPosts :
{{#each post in content}}
<p>{{post.body}} </p>
{{/each}}
Route:
App.AllPosts =Ember.Object.extend({
body : null
})
App.AllPostsRoute = Ember.Route.extend({
setupController : function(controller,model){
controller.set('content',model);
}
});
And controller as
App.AllPostsController = Ember.Controller.extend({
actions: {
save : fucntion(){
// Get And update data from server via ajax
}
}
});
I want to keep data in sync with data on server, for this i planned to use setInterval and call the save action above every 1000ms to update the data. But it doesn't work. i used setInterval like this
setInterval(App.AllPostsController.actions.save,3000);
I DONT want to use Ember Data. As the data is dependent on another Node app which runs server side.
You're trying to run an action on a type, not an instance of the controller. Instead you should start saving when you actually hit the route and controller, setupController is a good place to accomplish this.
App.AllPostsRoute = Ember.Route.extend({
setupController : function(controller,model){
controller.set('content',model); // in this code model would be blank, I'm assuming you're leaving out code
this.startSaving(controller);
},
willTransition: function(transition){
//if I'm leaving, this.stopSaving();
},
isSaving: false,
startSaving: function(controller){
this.set('isSaving', true);
this.realSave(controller);
},
realSave: function(controller){
if(!this.get('isSaving')) return;
Em.run.later(function(){
controller.send('save');
}
},
stopSaving: function(){
this.set('isSaving', false);
}
});
I am making an ajax call to controller to post data from view to controller.And in the receiving controller I am updating my model with new values.Now I want to bind this new model to view again in success call of $.ajax post.Please Suggest.
one way to do this is to return a partial view from the controller. You can replace the contents of your previous view with the new html content. Lets expand on this...
so, here is your controller action
[HttpPost]
public ActionResult SomeMethod(params...){
....
var model = some model;
...
return PartialView("ViewName",model);
}
and in the ajax, use
$.ajax({
url : #Url.Create("Action","Controller"),
type : 'POST',
data: { ... your data params ..},
success : function(result){
$("#ContainerId").html(result);
}
})
in the html you would need a div with the id = "ContainerId". The content would get swapped out by the html passed back in the success function.
The Model is only used in RAZOR when rendering the page. Once you get to the point where you are using AJAX, the model is no longer available to you.
What, exactly, are you trying to accomplish? Maybe there is another way to do it?
I am working on a project built in ASP.Net MVC 3.
In the index page I have displayed the data and allow the user to do inline editing using jeditable (which also uses ajax function) and delete function.
In the create page, obviously it allows the user to enter new the data but now I need to add a feature to allow the delete from the create page itself if the data already exists on the database.
Shows confirmation box if the data already exists (in my case if Extension is not available) on Extension's textbox blur.
I was using the ajax function for this feature but was not working, after spending hours on it, I was able to figure out the what was causing the problem.
The ajax function was working only on the Index page, not the other page. I renamed the Create page as Index and the original Index to something else, well it worked this time but ajax stopped working on the original Index page which was renamed to something else.
In the url if I load the index page as "http://localhost:1234/Controller/Index", the page loads fine but ajax functions do not work.
In a simple way:
Ajax functions works on
localhost:1234/Controller
Ajax functions do not work on
localhost:1234/Controller/Create
localhost:1234/Controller/ViewPage1
localhost:1234/Controller/Index
If someone could explain why its behaving like this, it would be great to have solution for this and whats the alternative solution for this if it can be fixed.
Thanks
Javascript code
$('#Extension').blur(function () {
$.post("CheckPeople/checkDelete",
{
Extension: this.value
},
function (data) {
alert(data);
});
});
Controller: VB Code
//GET: /People/
Function Index() As ViewResult
ViewBag.CurrentPage = "People"
Return View(db.Peoples.ToList())
End Function
//GET: /People/Create
Function Create() As ViewResult
Return View()
End Function
//POST: /People/Create
<HttpPost()>
Function Create(ByVal people As People) As ActionResult
If ModelState.IsValid Then
db.Peoples.Add(people)
db.SaveChanges()
Return RedirectToAction("Index")
End If
Return View(people)
End Function
Public Function checkDelete(ByVal Extension As String) As JsonResult
Dim result As String = "I got you "
Return Json(result, JsonRequestBehavior.AllowGet)
End Function
Thanks for the comments, I added the code, its straight forward.
If I rename the Create.vbhtml to Index.vbhtml and commented the original Index routing and rename both post and get Create routing to Index, ajax works fine.
I think its a relative url issue.
try adding a / in front of the ajax request url, like
$.post("/CheckPeople/checkDelete",
{
Extension: this.value
},
function (data) {
alert(data);
});
});
hope this helps.