ASP.NET MVC and Ajax slow? - asp.net-mvc

I've just started out trying MVC 2 and Ajax, and I'm wondering if I'm doing something wrong, because I was under the impression that Ajax would make changes in a webpage very fast. The example I have is with the Ajax actionlink:
<div>
<%: Ajax.ActionLink("Dita", "AjaxView", new AjaxOptions { UpdateTargetId = "myDiv" })%>
</div>
<div id="myDiv">
Change this text</div>
And the Action method:
public ActionResult AjaxView(string id)
{
return Content("Text changed!"); ;
}
This is a rather short simple text string, and still it takes about 1-2 seconds before the text shows up. Maybe ajax isn't supposed to do what I thought it would, but I was thinking I could use it for instant previews of text and images sort of like a rollover function (by the way I was wondering if the actionlink can be set to invoke the action method on mouseover rather than click?)
Is it normal that it is this slow or am I missing something?

It might be an IPv6 DNS resolution issue with FF and Chrome when working with localhost. Fixes described here:
Firefox and Chrome slow on localhost; known fix doesn't work on Windows 7
and here
https://superuser.com/questions/174715/is-there-a-way-to-disable-ipv6-in-googles-chrome
I would try in IE and Opera first to check if it works faster.
Note: if that's actually the problem, this has nothing to do with AJAX.

I think you've misunderstood slightly.. There is nothing about AJAX that will necessarily make your Web application faster. What AJAX does is to only load the information you need instead of loading the entire page over again. That way you can make subtle changes to the page you're viewing without having to refresh the entire page.
The point being - when you call AjaxView it still has to do a call back to the server which will take time no matter what you do. The reason why this action is slow might rely on different factors;
- Your server might be busy doing something else, hence consuming resources
- You just built the assembly, making the call slower the first time around

Related

Isn't ASP.NET MVC _layout.cshtml similar to Webforms Master page?

I have an MVC 4 project with a layout page that I have setup with images that are links like this
<img id="logoImage" src="~/Content/siteImages/myLogo.png" alt="My logo" title="Welcome to my site" />
I have also tried this:
<img id="logoImage" src="../Content/siteImages/myLogo.png" alt="My logo" title="Welcome to my site" />
And this:
<img id="logoImage" src="#Url.Content("~/Content/siteImages/myLogo.png")" alt="My logo" title="Welcome to my site" />
These all work fine as long as the controller is the home controller. I use an Actionlink #Html.ActionLink("Northwind Demo", "Northwind", "Northwind", null, new { #class="links"}) to get to another controller.
As soon as the ActionLink is clicked, my images disappear. I examined the rendered link text in the browser and it is the same as it was before.
src="Content/siteImages/myLogo.png"
However, when examining the request in the network tab of the browser the url for the image is now
Northwind/Content/siteImages/myLogo.png
which does not resolve. For some reason the browser is adding the name of the controller to the beginning of the request for the image. I am sure that I am missing something really dumb but...
How do I fix this?
Edit
I wonder if this is an issue that only happens when running locally and may disappear when deployed to a server? I am still unable to fix this.
Edit
I am really struggling with the fact that no one else has encountered this before. I was under the impression that _layout.cshtml was like a master page in WebFroms. I need some suggestions here.
EDIT
So I had a moment of success. I changed the name of the entry method into the Northwind controller to Index and the images displayed properly in the index view. However, if I call another view, then the images disappear again.
I use radion buttons to select a different view based on which one is selected like this:
public ActionResult Search()
{
int id = Convert.ToInt32(Request.Form["radio"]);
switch (id)
{
case 1:
return View("Customer");
case 2:
return View("Orders");
case 3:
return View("Employees");
default:
ViewBag.Error = "Search parameter not found";
return View("Index");
}
}
I am still not able to fix this but I think that I am closer to a solution with someone's help.
Thanks in advance
Don't use relative addressing in MVC, since as you can tell you run into problems because views can be accessed from multiple routes (ie, /, /Home, /Home/Index, etc.. are all the same view, but different paths, if you use ../whatever then /Home/Index becomes /Home/whatever, / and /Home become /whatever)
Always use either #Url.Content to generate urls if you're not in a Razor 2+ view. If you're in Razor 2 or greater, then you can use src="~/Content/images/whatever"
If these methods are not working, then you need to look at your Application root, web.config, etc.. because MVC is becoming confused about where the root of the site is.
Well I have figured this out and I feel like an idiot! I have a script file that I use to change the images when it becomes small enough so that they continue to fit on the screen as it gets smaller for a responsive design. Like this:
$("#logoImage").attr("src", "Content/siteImages/logoSmall.png");
Well, the missing / at the very beginning is what was causing the issue. Adding the / fixed all my issues. Like this:
$("#logoImage").attr("src", "/Content/siteImages/logoSmall.png");
Even though I feel very silly at this moment, I am posting my answer in case someone else comes along and has a similar issue. Don't forget your script files and don't leave anything out when trying to fix a weird issue. Thanks to everyone that looked at this and tried to help.

What kind of questions should be asked when choosing between straight MVC4 and a SPA framework like Durandal or Angular?

I'm in the middle of making this choice right now and I don't know what kinds of questions I should be asking. One that I believe is valid:
Do I need SEO / natively crawlable pages? If so, stick with MVC4.
One question that I'm not sure about is the impact on performance - I think this is valid:
Is initial load time very important? If so, stick with MVC4 (like stackoverflow).
What are some other questions that should be asked that can help point a developer in the right direction here?
PS - if this question is being asked in a way that doesn't meet quality standards, I'd appreciate any help modifying it so that it does.
I have been asked and had to be a part of decision making groups recently that made this same decision. Here is what was important for us -
How many of the devs that will be working are familiar with MVC4 vs Javascript?
How much is performance an issue? (Is single page app really necessary?)
How big is the data we will be working with? (Remember that extremely large data sets don't work well in a spa)
Durandal requires using a lot of different libraries - is it ok to have to learn each of the different usages? Each library is important in its own regard and you must know when and why to use each library.
Angular is very set in its ways and harder for a new javascript dev coming from c# and .net to understand, are you willing to provide time for learning?
Last, which browsers are you targeting? Ie6+ works great with mvc4 and durandal, angular needs some massaging.
Hope this is helpful!
Why not combine the best of both worlds? SPA and straight MVC!
I was also investigating a lot of time in durandal, sammyjs, angular frameworks. I then decided to go with sammy.js for just the routing. This way I could still make use of the easy MVC 4 razor view engine to generate my views at server side. Even though it would be more performant to generate your html and bindings at client side by using knockout, I felt more secure by doing this at the server side.
But then of course you have to deal with those hashbangs? Therefor I started to investigate more time into the history.js (or HTML 5 history API). And then things got clear to me.
My solution
What is the essential part of a SPA? Well, in fact, that your layout.cshtml is only loaded once right. From then on you you only want to load content from the server and display it in the main content div. Does it need to be json? No, in fact it does not.
By default MVC 4 controllers returns an html string. So what if your < a href="">< /a> tags would be intercepted by a simple jQuery script to get the html string from the controller and load it into a div.
I went even further and wrote my own jQuery engine on top of the HTML 5 history api. I just intercept every link that is clicked and load the content from its href attribute and then place it into the desired div. Further I push the URL with history api pushSate. Another big advantage of this approach is that your application is not broken when javascript is disabled or when HTML 5 is not supported.
My views have the following layout page:
#{
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}
This way when javascript is disabled or html 5 is not supported, the view will render inside the _Layout.cshtml.
This also allows for URL linking. The link will hit the address bar and will be routed to the controller. As this is not an ajax request, the view will render with _Layout.cshtml.
But once your _Layout.cshtml and javascript is loaded correctly and once, all < a href="">< /a> will be intercepted, loaded by AJAX (partial with layout = null) into the content div and the url is pushed on the address bar. So it seems that you are at that location, but in fact you are not. It's just an illusion to make things more responsive and efficient. Et voila, SPA in straight MVC.
The minimum routing code would be something like this
Interception of Links
$('.spalink').click(function () {
$.ajax({
url: this.href,
success: function (content) {
$('body>#content').css({ opacity: 0 });
$('body>#content').html(content);
$('body>#content').animate({ opacity: 1 }, 300, 'swing');
history.pushState({ state : 'spa' }, null, this.href);
}
});
return false;
});
BACK and FORWARD event
window.addEventListener("popstate", function (e) {
if (e.state != null) {
$.ajax({
url: location.href,
success: function(content) {
$('body>#content').css({ opacity: 0 });
$('body>#content').html(content);
$('body>#content').animate({ opacity: 1 }, 300, 'swing');
},
cache: false
});
return false;
}
});
return true;
}
PS: if you don't feel like writing your own SPA engine, take a look at history.js (it does the same out of the box)
Ajaxify on top of History.js on top of HTML 5 history API

Refresh the browser once on load or clear DOM

I have a dynamic MVC4, jQuery Mobile application that works for the most part quite well. I have an auto posting dropdown list that selects a list from the database via the following code.
<script type="text/javascript">
$(function () {
$("#TownID").live('change', function () {
//$("#TownID").change(function () {
var actionUrl = $('#TheForm1').attr('action') + '/' + $('#TownID').val();
$('#TheForm1').attr('action', actionUrl);
$('#TheForm1').submit();
});
});
</script>
<p>
#using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" }))
{
#Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town")
}
</p>
The problem is it only works properly the first time a search is performed unless I click refresh. I don’t think this has anything to do with MVC, I think the problem is with AJAX and jQuery Mobile.
Edit:
The first time I search www.mysite.com/Home/Search/2 yields a result and woks fine, but the second time something seems to be left behind in the DOM??? and it looks for:
www.mysite.com/Home/Search/2/2 also
I get 404 errors in my log and “Error Loading Page” but it still finds the results and displays the page correctly!
Then with a third search I get the error 404’s in my log and “Error Loading Page” but it has grown and now looks for:
www.mysite.com/Home/Search/2/2
www.mysite.com/Home/Search/2/2/2 also
This then continues to grow after every search until at some seemingly random point on each test, it seems to give up and I get error 505
Additional Edit:
The code works perfectly if I take jQuery Mobile out of the question
Can anyone tell me what might be going on here?
Get rid of: $(function () {
And replace it with: $(document).delegate('[data-role="page"]', 'pageinit', function () {
Please read the big yellow sections at the top of this page: http://jquerymobile.com/demos/1.1.0/docs/api/events.html
You can't rely on document.ready or any other event that only fires once per page. Instead you have to get used to using jQuery Mobile's custom page events like pageinit so your code will work no-matter when the page is added to the DOM (which you don't know when this will happen in a jQuery Mobile website). There are a ton of events, so again, please read the documentation I linked-to above.
Firstly, dynamically generated html using a server side templating engine blows. I really don't understand what value people see in it.
My guess is that it used to make sense 10 years ago before AJAX became popular, and has just hung in there ever since because people have this feeling that it is "the right way to do it". It isn't. ESPECIALLY for mobile web apps.
Secondly, it looks like you are trying to do pretty simple search. All this MVC4 garbage makes it difficult for you to see what is really happening though. You don't need to append parameters to your URL for a simple form submission like this. In fact your TownId should already be part of the POST data when you submit, so you can just remove the URL modification bit.
Alternatively, don't use a form submission, but just a GET and AJAX. I don't know what your app is doing here, but I imagine you want to display the results on the page dynamically somehow, so a GET is more than enough.
Use your developer browser tools (F12) to see what exactly is getting submitted when you do the submit - it really helps. And for your next project, abandon MVC4! "Well established design patterns" my foot.
I have been bothered by this problem for a long time
There are same select element in the DOM I think so...
and I used $('.SelectCSS:last').val()
It seen work well.
I come from China , English is poor...
I guess this is one for the future, MVC and jQuery Mobile don't seem to blend completely right now. Maybe MS's response to the issue is Single Page Applications!
SPA may satisfy Danial also?

rails 3: (probably ajax question) need embeddable a banner on a html page that pulls a different 'joke' from our app every N seconds

I've never done ajax stuff myself, and this seems like an ideal feature to add to my app to learn how to do it...
My app maintains a database of jokes.
I'd like to provide a simple way for anyone to add a small banner to the html on their webpage that will display a new joke every N seconds.
It seems the two approaches are:
1) iframe where the url/view hit by the iframe has a meta refresh tag and randomly pulls a joke each time the url is hit. But iframes can resize to fit content, and I'm not sure if browsers will refresh the contents of the iframe.
2) the right way ... ajax. But I have no idea if this is a "big" or "trivial" job for a rails 3 app, and no idea where to get started.
Any pointers on doing this would be deeply appreciated!
I'll use jQuery for this example but the overall technique should work pretty much the same with any other AJAX framework.
In your JavaScript, you'll want to use $.ajax to grab a new quote from your server and setTimeout to get periodic updates; something like this:
var n_seconds = 5; // Or whatever you want.
var timer = null;
function replace_quote() {
// Do a $.ajax call to your server.
$.ajax({
url: '/some/route',
type: 'get',
dateType: 'htm;',
success: function(data) {
// Replace the quote with the new one.
$('#quote-container').html(data);
// And restart the timer.
timer = setTimeout(replace_quote, 1000 * n_seconds);
}
});
}
replace_quote();
If you start out with an empty quote box then you can simply call replace_quote() to give it an initial value through your AJAX call.
You could also use setInterval to call your quote replacer. Then you wouldn't need to manually restart the timer with the setTimeout call but you would run the risk our updates fighting each other if an AJAX call takes longer than n_seconds.
If you still want to provide a link for updating the quote then bind the link to a JavaScript function something like this:
function manually_replace() {
clearTimeout(timer);
replace_quote();
}
Calling clearTimeout will, effectively, reset the timer when they change the quote themselves.
Then, in your Rails app, you'd add a route for /some/route and the controller would simply grab a random quote from your database and then use render :partial => 'quote' to send back just the HTML snippet for the quote without all the usual layout wrapping.
Handling AJAX requests in Rails (or any other framework) is pretty much the same as handling any other request, the only difference is that you won't send back a full page, you just send back a little piece of HTML or a blob of JSON (or XML) for the client to process and render. Hence the size difference between the client-side and server-side outlines above.

Structuring complex web forms in ASP.NET MVC

What is a good approach in ASP.NET MVC for implementing a complex form where sections of the form are shown and hidden based on a user's inputs?
My background is in Webforms. I am frequently asked to build forms where a user selects an option from a dropdown list, triggering a handful of new fields to appear. A different selection might cause a different set of fields to appear.
In the past, I would handle this scenario via an UpdatePanel and a wrapper Panel around the fields that I want to show or hide. Validation is automatically disabled when the fields are hidden.
Going forward, I'd like to make use of MVC's attribute-based model validation, but is it possible to make the validation conditional on the values of other properties?
Also, how can I handle the toggling of blocks of form fields? I know how to do it manually in jQuery, but I'm hoping there's an approach that ties in with validation and server-side code.
I am liking MVC much better overall, but I haven't figured out how to handle this type of scenario very well. Likely I just need to shift my thinking to fit better with the MVC approach.
Josh,
The first thing I's suggest is to make sure you use ViewModels for the pages that are mode complicated. A ViewModel is basically a Model you create for a specific View; for example, a ViewModel could be a composition of other classes.
As for dynamically changing the fields on your View, the best way is to use jQuery (or any other javascript library) to do it.
I also migrated from a web form environment and I know is difficult to change gears at the begining, but trust me, doing a simple jQuery even handler is much simpler than having to put in place a control panel and then the event handlers.
Not to mention that is much more efficient; update panels are after all making partial posts to the page, sometimes, with jQuery you don't even need to do that.
After a few projects with MVC, I actually now find it time consuming to go and do the Update Panels on web forms ;)
Hope this helps,
-Covo
I know this might not be the answer you're looking for, but I personally don't think complex forms are very user friendly in the first place and I always try to split them up into simpler forms where possible, or to simplify the form. I've come across many forms in websites where there are a raft of "fields" where there should really be a few questions for the user to answer. Simple stuff which gets to the point of what they want to achieve rather than the field values, along with a lot of application specific knowledge needed to set those fields to the right values.
If you still want to go ahead with a complex form, then as the other answers have already stated there are facilities provided by MVC to do that, but there isn't any set way. So, it's down to you to figure out what will work best for your users.
Traditional asp.net webforms did alot of "magic" for you whereas you have to be aware of the work that goes into creating the "magic" in asp.net MVC. The benefit is that with MVC you have more control over what is happening which can also enhance performance.
In asp.net webforms an UpdatePanel is used for ajax calls. If you need to got to the server asynchronously(without doing a full post back) then use ajax via JQuery. See below for example:
$.ajax({
type: "get",
url: "/YourController/YourAction",
success: function (obj) {
//any logic you want to do upon success
}
});
The above example will do an ajax HTTP GET call to /YourController/YourAction.
In order to handle "toggling of blocks", if you don't need to go to the server for data and you simply want to do it on the client, then use simple jquery. JQuery has a function for toggling items.
http://api.jquery.com/toggle-event/
Because of the way MVC works in contrast to Webforms you're stuck with the responsibility of really thinking about what happens on the client and what happens on the server separately as not a lot of meta-data is being passed back to give us that happy Webforms feeling.
However, there is a notion when using the built-in AJAX libraries when you render a form that you can have it auto do an update once it is posted. In a sense, it's saving you the JavaScript/JQuery because it "auto-wires" it up similar-ish to a Panel. In this way you could potentially look at progressively rendering your complex forms from the server as each section is edited, etc.
See MSDN: http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.updatetargetid.aspx
The relevant code example to give you an idea (unfortunately, it's not in the more readable Razor syntax):
The relevant line is the Ajax.BeginForm where the form tag is rendered. Once the form is posted, the MS AJAX library will auto update the element specified in "UpdateTargetId" specified in the form's AjaxOptions. In this case, the response will be placed into the SPAN element "textEntered" upon reply from the server. Here, you could progressively render more content to the user to fill out, perhaps another form, etc.
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
Page Rendered: <%= DateTime.Now.ToLongTimeString() %>
</p>
<span id="status">No Status</span>
<br />
<%= Ajax.ActionLink("Update Status", "GetStatus", new AjaxOptions{UpdateTargetId="status" }) %>
<br /><br />
<% using(Ajax.BeginForm("UpdateForm", new AjaxOptions{UpdateTargetId="textEntered"})) { %>
<%= Html.TextBox("textBox1","Enter text")%>
<input type="submit" value="Submit"/><br />
<span id="textEntered">Nothing Entered</span>
<% } %>

Resources