Ajax.ActionLink in MVC3 is getting slow after a number of requests - asp.net-mvc-3

I have this simple MVC 3 application which simply has two controllers(Home and Edit), two actions one per controller and two views for each action,
each one of the views has an ajax action link which simply request the other view and displays the result in a div, the problem is that after a certain number of requests the page is getting slower, I checked that with fiddler and noticed that each time I press the action link the request will be send multiple times according to the equation (2 to the power n) where n is how many time the link was pressed, find below the controllers and views.
the Controllers
public class EditController : Controller
{
public ActionResult Index()
{
return View();
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Text = "Home Page";
return View();
}
}
And the views
Home View
#{
ViewBag.Title = "Home";
}
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script type="text/javascript">
function myCallback(xhr, status) {
alert(status);
}
</script>
<div id="divLoading" style="display: none">
Loading ...</div>
<div id="divResultText">
#Ajax.ActionLink("Edit Ajax", "Index", "Edit", null, new AjaxOptions
{
HttpMethod = "Get",
OnComplete = "myCallback",
UpdateTargetId = "divResultText",
LoadingElementId = "divLoading"
})
</div>
Edit View
#{
ViewBag.Title = "Edit";
}
#Ajax.ActionLink("Home", "Index", "Home", null, new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId = "divResultText",
LoadingElementId = "divLoading"
})

I have got the answer in
Ajax.ActionLink in MVC3 is getting slow after a number of requests

Related

Adding 'Edit' Ajax.ActionResult to render on same page in MVC

My first ever Ajax request is failing, and I'm not quite sure as to why.
I've used the MVC scaffolding in order to create a table (which uses a default #Html.Actionlink). However, I'm looking to include an 'edit' section on the same page via ajax requests.
So my table now has:
<td>
#Ajax.ActionLink("Edit", "Edit", new { id=item.OID}, new AjaxOptions {
UpdateTargetId = "editblock",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET" }
) |
As suggested here.
Within the same view i have a div defined as:
<div id="editblock">
Edit Section Here
</div>
And My controller is defined as:
public PartialViewResult Edit(int? id)
{
if (id == null)
{
return PartialView(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
}
TableModel tablevar = db.TableModel.Find(id);
if (tablevar == null)
{
return PartialView(HttpNotFound());
}
return PartialView("Edit", tablevar );
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult Edit( TableModel tablevar )
{
if (ModelState.IsValid)
{
db.Entry(tablevar ).State = EntityState.Modified;
db.SaveChanges();
}
return PartialView("Edit",tablevar );
}
My "Edit.cshtml" looks like:
#model Project.Models.TableModel
<body>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
Could anyone suggest as to why this is failing, and what I should be doing instead to render this partial view onto the page (as currently it keeps redirecting to new page and not showing on 'index' screen)?
Place those scripts at the bottom of your view. By the time they execute your form isn't present (and therefore the auto-wireup fails). In general, you want <script> tags as close to the </body> tag as possible to your content is there before the script executes.
Other than that, you look fine.

AJAX pagedlist with partial view

I can't quite figure out how to get a partial view to render a paged list using ajax.
The closest I've got it to working is the example from Using paging in partial view, asp.net mvc
I'm basically trying to create a page with a list of comments per user where the page can be changed in the same way as the answers tab on the stackoverflow users page.
The paging works fine the on the first pager click, but then the the partial view is all that is returned once I click on the pager again.
Controller:
public class ProductController : Controller
{
public IQueryable<Product> products = new List<Product> {
new Product{ProductId = 1, Name = "p1"},
new Product{ProductId = 2, Name = "p2"},
new Product{ProductId = 3, Name = "p3"},
new Product{ProductId = 4, Name = "p4"},
new Product{ProductId = 5, Name = "p5"}
}.AsQueryable();
public object Index()
{
return View();
}
public object Products(int? page)
{
var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
var onePageOfProducts = products.ToPagedList(pageNumber, 3); // will only contain 25 products max because of the pageSize
ViewBag.OnePageOfProducts = onePageOfProducts;
return PartialView("_Products");
}
}
Views:
Index.cshtml:
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<h2>List of Products</h2>
<div id="products">
#Html.Action("Products", "Product")
</div>
#section scripts{
<script type="text/javascript">
$(function() {
$('#myPager').on('click', 'a', function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(result) {
$('#products').html(result);
}
});
return false;
});
});
</script>
}
_Products.cshtml:
#using PagedList.Mvc;
#using PagedList;
<ul>
#foreach(var product in ViewBag.OnePageOfProducts){
<li>#product.Name</li>
}
</ul>
<!-- output a paging control that lets the user navigation to the previous page, next page, etc -->
<div id="myPager">
#Html.PagedListPager((IPagedList)ViewBag.OnePageOfProducts, page => Url.Action("Products", new { page }))
</div>
Model
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
}
Can anyone show me what I'm doing wrong?
I ended up using the unobtrusive ajax example from the pagedlist source [https://github.com/troygoode/PagedList][1]
partial view:
#using PagedList;
#using PagedList.Mvc;
<ul id="names" start="#ViewBag.Names.FirstItemOnPage">
#foreach(var i in ViewBag.Names){
<li>#i</li>
}
</ul>
#Html.PagedListPager((IPagedList)ViewBag.Names, page => Url.Action("Index", new { page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing( new AjaxOptions(){ HttpMethod = "GET", UpdateTargetId = "unobtrusive"}))
Index:
#{
ViewBag.Title = "Unobtrusive Ajax";
}
#using PagedList;
#using PagedList.Mvc;
#Styles.Render("~/Content/PagedList.css")
<h2>Unobtrusive Ajax</h2>
<p>Example of paging a list:</p>
<div id="unobtrusive">
#Html.Partial("UnobtrusiveAjax_Partial")
</div>
Controller:
public class UnobtrusiveAjaxController : BaseController
{
// Unobtrusive Ajax
public ActionResult Index(int? page)
{
var listPaged = GetPagedNames(page); // GetPagedNames is found in BaseController
if (listPaged == null)
return HttpNotFound();
ViewBag.Names = listPaged;
return Request.IsAjaxRequest()
? (ActionResult)PartialView("UnobtrusiveAjax_Partial")
: View();
}
}
Just in case, since the original question wasn't answered. I guess the problem was that on click handlers weren't reattached to the new pager elements generated by AJAX request. I also don't like unobstrusive AJAX solution in this case, since pager id is hardcoded in the nested view while passing it in some other way may be too cumbersome.
<script type="text/javascript">
// better not to clutter global scope of course, just for brevity sake
var attachHandlers = function() {
$('#myPager a').click(function() {
$('#myPager').load(this.href, function() {
attachHandlers();
});
return false;
});
};
$(document).ready(function () {
attachHandlers();
});
</script>

Result not showing with unobtrusive ajax in mvc 3

I'm trying to implement a little ajax using unobtrusive ajax of mvc 3. Here is the code snippet:
Controller:
[HttpGet]
public ActionResult ViewEmployee()
{
return View();
}
[HttpPost]
public ActionResult ViewEmployee(EMPLOYEE model)
{
var obj = new EmployeeService();
var result=obj.FindEmployee(model);
return View("ViewEmployee", result);
}
View:
#{AjaxOptions AjaxOpts = new AjaxOptions { UpdateTargetId = "ajax", HttpMethod = "Post" };}
#using (Ajax.BeginForm("ViewEmployee", "Home", AjaxOpts))
{
#Html.LabelFor(x => x.EmployeeID)
#Html.TextBoxFor(x => x.EmployeeID)
<input type="submit" name="Find Name" value="Find Name" />
}
<div id="ajax">
#{
if (Model != null)
{
foreach (var x in Model.EmployeeName)
{
#x
}
}
else
{
#Html.Label("No Employee is selected!")
}
}
</div>
I debugged the code, its sending the employee id to the ViewEmployee method, finding the name but not being able to display the name back into the view.
I've activated the unobtrusive ajax property in web.config & imported the scripts into the view.
Whats going wrong with this? Please help.
This is simple but effective article, ask me if you have any more question! I resolved the problem! By the way, whats wrong with stackoverflow, i'm not getting no response literally!
http://www.c-sharpcorner.com/UploadFile/specialhost/using-unobtrusive-ajax-forms-in-Asp-Net-mvc3/

mvc partial view ajax update returning the partial view as a page

I have a partial view that upon adding an item to the database needs to update.
The Index.cshtml:
#using (Ajax.BeginForm("Index", "WinEntry", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "wingrid", InsertionMode = InsertionMode.Replace}))
{
#Html.Partial("_winVenue")
#Html.Partial("_singleWin")
}
<div id="wingrid">
#Html.Partial("_wingrid")
</div>
The _singleWin has the submit button
The controller:
[HttpPost]
public ActionResult Index(Win win)
{
win.dealerId = "1234567890";
win.posterid = "chris";
win.posttime = DateTime.Now;
wem.addWin(win);
IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
return PartialView("_wingrid",w);
}
When the controller returns the partial view _wingrid it returns it as a new page and the behavior I am looking for is like an update panel inside the wingrid div.
Any help would be appreciated.
You already seem to be doing this thanks to the UpdateTargetId = "wingrid" option in your AJAX form. Just make sure that you clear values that you modify in your POST controller action form the modelstate. Otherwise HTML helpers could still use the old values:
[HttpPost]
public ActionResult Index(Win win)
{
ModelState.Remove("dealerId");
win.dealerId = "1234567890";
ModelState.Remove("posterid");
win.posterid = "chris";
ModelState.Remove("posttime");
win.posttime = DateTime.Now;
wem.addWin(win);
IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
return PartialView("_wingrid",w);
}
Also don't forget to include the jquery.unobtrusive-ajax.js script to your page if you want your Ajax.* helpers to work:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

problem asp.net mvc cannot load ajax content

in my view:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../jquery-1.4.1-min.js" type="text/javascript"></script>
<%= Ajax.ActionLink("Update", "Index", "Home", new AjaxOptions { UpdateTargetId = "time" })%>
<br />
<div id="time">
<% Html.RenderPartial("TimeControl"); %>
</div>
in my controller:
[HttpGet]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
// Normal Request
if (!Request.IsAjaxRequest())
{
return View("Index", model);
}
// Ajax Request
return PartialView("TimeControl");
}
in my model:
public HomeModel()
{
Time = DateTime.Now;
}
i think everything is ok, but if iam clicking update link, time will be not updated.. why?
it schould be actual if i click update link
I suggest you do the following:
[HttpGet]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
return View("Index", model);
}
[HttpPost]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
// Ajax Request
return PartialView("TimeControl");
}
I think the problem might be that the AJAX request is a POST.
You may simply try to (1) remove [HttpGet] or (2) set the HttpMethod in the AjaxOptions to "GET".
Ajax.ActionLink("Update", "Index", "Home", new AjaxOptions { UpdateTargetId = "time", HttpMethod = "get" })
That should solve the problem.
(3) If it doesn't, check if you are using the correct overload. This should work:
Ajax.ActionLink("Update", "Index", "Home", null, new AjaxOptions { UpdateTargetId = "time" }), null)
Any of the options in my previous answers could solve your problem if the AJAX isn't working correctly with your application.
Buy in your example, you're also using something that wasn't quite clear to me.
You use a constructor overload that takes the url. And you use the default constructor to set the time. Is the constructor you use (the one that takes the url) also calling the parameterless constructor?
That constructor should do something like this:
public HomeModel(paramter.......) : this()
{
// Whatever...
}

Resources