Search Results

Search found 25175 results on 1007 pages for 'classic asp'.

Page 13/1007 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Edit and Continue does not Work in VS 2010 / ASP.Net MVC 2

    - by Eric J.
    Although Enable Edit and Continue is checked on the Web tab of my ASP.Net MVC 2 project, I cannot in fact change the source code while running. For example, if I try to edit a controller while paused in the debugger, I cannot change the file (acts as if read only). I found a related post Edit and continue in ASP.NET web projects, however The answers seem to suggest I should be able to at least edit the code, then reload the page to see the result. I don't know what the distinction is between a Web Application and Web Site projects Any guidance is appreciated.

    Read the article

  • Invalid padding on ASP 2.0 cookie, MVC looks ok

    - by brian b
    We have a cookie management library that writes a cookie containing some sensitive information, encrypted with Rijndael. The cookie encrypts and decrypts fine in unit tests (using Moq), works fine for MVC web applications, but when called from an ASP.net 2.0 website, the cookie cannot be decrypted. "Padding is invalid and cannot be removed." We are sure that the cookie value is valid because we tested it 10,000 times with random data in a unit test. There is something about what ASP.NET 2.0 does when it reads and writes the cookie that causes trouble. There has to be a gotcha. Any suggestions?

    Read the article

  • ASP.NET MCV 2, re-use of SQL-Connection string

    - by cc0
    Hi, so I'm very very far from an expert on MVC or ASP.NET. I just want to make a few simple Controllers in C# at the moment, so I have the following question; Right now I have the connection string used by the controller, -inside- the controller itself. Which is kind of silly when there are multiple controllers using the same string. I'd like to be able to change the connection string in just one place and have it affect all controllers. Not knowing a lot about asp.net or the 'm' and 'v' part of MVC, what would be the best (and simplest) way of going about accomplishing just this? I'd appreciate any input on this, examples would be great too.

    Read the article

  • Configuring Multiple ASP.NET MVC Sites To Use a Single Database For Authentication/Membership

    - by Maxim Z.
    Is it possible for two or more ASP.NET MVC sites to use a single SQL Server database for authentication and other things? Here's how I'm thinking of setting it up: I will combine the current database of each site into one single database, prefixing the tables with the name of the site they belong to. I currently have authentication tables generated by the asp.net_regsql.exe utility. How should I combine those tables? I'm guessing that the way to do it is to somehow set the "application_id" column in those tables... Thanks in advance.

    Read the article

  • Is it possible to share session state between asp.net aspx page making a call to an asp.net webservi

    - by Greg Balajewicz
    My Situation: I have 1 asp.net application with both aspx pages AND webservices I make calls (using ajax) to the webservice from an aspx page - all within the same asp.net application! Here is my problem/question Is there any way to share the session state? I.e. - the aspx page has a sessionID and the state is being maintained. When the call to the webservice is made, is there a way to automatically send the seesionID to the webservice and then be able to access the same session state from the webservice? -- That would greatly simplify my work! :) Many thanks for your ideas!!

    Read the article

  • What's missing in ASP.NET MVC?

    - by LukaszW.pl
    Hello stackoverflow, I think there are not many people who don't think that ASP.NET MVC is one of the greatest technologies Microsoft gave us. It gives full control over the rendered HTML, provides separation of concerns and suits to stateless nature of web. Next versions of framework gaves us new features and tools and it's great, but... what solutions should Microsoft include in new versions of framework? What are biggest gaps in comparison with another web frameworks like PHP or Ruby? What could improve developers productivity? What's missing in ASP.NET MVC?

    Read the article

  • ASP.NET 4.5 Bundling in Debug Mode - Stale Resources

    - by RPM1984
    Is there any way we can make the ASP.NET 4.5 Bundling functionality generate GUID's as part of the querystring when running in debug mode (e.g bundling turned OFF). The problem is when developing locally, the scripts/CSS files are generated like this: <script type="text/javascript" src="/Content/Scripts/myscript.js" /> So if i change that file, i need to do a hard-refresh (sometimes a few times) to get the file to be picked up by the browser - annoying. Is there any way we can make it render out like this: <script type="text/javascript" src="/Content/Scripts/myscript.js?v=x" /> Where x is a GUID (e.g always unique). Ideas? I'm on ASP.NET MVC 4.

    Read the article

  • Classic ASP result set - ultimate confusion!

    - by Paul
    Consider a simple result set from a mysql query. rs("description") and rs("description").Value should be considered as the same thing. However, depending on how you access them, you get different results (!!) Access rs("description") directly and you are returned a "Field" object. Or, more importantly, use it directly in a call, and you are returned a "Field" object. mydescription = rs("description") + " is the description" Assign it to another variable, and the Value of that object is assigned... mydescription = rs("description") the contents of "mydescription" is a string. Why this difference? At one point in the life of ASP they must have both worked exactly the same, so why have they changed, and how can I change it back?

    Read the article

  • Classic ASP - How to convert string to UTF8 to USC2

    - by Brian G
    I have a problem where I am storing a UTF8 string in SQL Server as USC2, when I pull it out to display on a page with content-type set to UTF-8 it works fine. But I have a third party javascript component which when I pass it the string for the database it renders it as USC2. or not UTF8. Is there a way in ASP to convert this string to UTF-8 after reading it from the database to pass it to the third party component ( obfuscated ) . Hope this makes sense.

    Read the article

  • Partial view links not working in Fire Fox

    - by user329540
    I have a MVC4 asp.net application, I have two layouts a main layout for the main page and a second layout for the nested pages. The problem I have is with the second layout, on this layout I call a partial view which has my navigation links. In IE the navigation menu displays fine and when each item is clicked it navigates as expected. However in FF when the page renders the navigation bar is displayed but it has no 'click functionality' if you will its as if its simply text. My layout of nested page: <header> <img src="../../Images/fronttop.png" id="nestedPageheader" alt="Background Img"/> <div class="content-wrapper"> <section > <nav> <div id="navcontainer"> </div> </nav> </section> <div> </header> The script to retreive partial view and information for dynamic links on layout page. <script type="text/javascript"> var menuLoaded = false; $(document).ready(function () { if($('#navcontainer')[0].innerHTML.trim() == "") { $.ajax({ url: "@Url.Content("~/Home/MenuLayout")", type: "GET", success: function (response, status, xhr) { var nvContainer = $('#navcontainer'); nvContainer.html(response); menuLoaded = true; }, error: function (XMLHttpRequest, textStatus, errorThrown) { var nvContainer = $('#navcontainer'); nvContainer.html(errorThrown); } }); } }); </script> May partial view: @model Mscl.OpCost.Web.Models.stuffmodel <div class="menu"> <ul> <li><a>@Html.ActionLink("Home", "Index", "Home")</a></li> <li><a>@Html.ActionLink("some stuff", "stuffs", "stuff")</a></li> <li> <h5><a><span>somestuff</span></a></h5> <ul> <li><a>stuffs1s</a> <ul> @foreach (var image in Model.stuffs.Where(g => g.Grouping == 1)) { <li> <a>@Html.ActionLink(image.Title, "stuffs", "stuff", new { Id = image.CategoryId }, null)</a> </li> } </ul> </li> </ul> </il> </ul> </div> I need to know why this works fine in IE but why its not working in FF(all versions). Any assistance would be appreciated.

    Read the article

  • ASP.Net MVC2 (RTM) breaks response filtering - "Filtering is not allowed"

    - by womp
    I've just done a test run of upgrading a project to ASP.Net MVC 2 (RTM) in anticipation of the full official .Net 4.0 release coming later this month. Our application is using a minimizer for our CSS and javascript. To do so, it is making use of the HttpResponse.Filter property to set a custom filter. With the upgrade, the setter for this property is throwing an HttpException saying "Filtering is not allowed." Looking that the HttpResponse.Filter property in reflector shows this: set { if (!this.UsingHttpWriter) { throw new HttpException(SR.GetString("Filtering_not_allowed")); } ... private bool UsingHttpWriter { get { return ((this._httpWriter != null) && (this._writer == this._httpWriter)); } } Clearly something has changed in the way the HttpResponse is writing to the output stream in MVC2. Does anyone know what the change is, or at least a workaround for this? EDIT: This seems pretty radical. Some further investigation shows that ASP.Net MVC 2 RTM is using a System.Web.Mvc.ViewPage.SwitchWriter as the Output property of an HttpResponse, whereas MVC 1 was using a plain old HttpWriter. That explains why the exception is being thrown. But that doesn't explain why they've chosen to completely break this functionality. This thread seems to indicate that this is just temporary... but this makes me pretty nervous... this is the RTM after all. Any further comments appreciated on this.

    Read the article

  • Support for nested model and class validation with ASP.NET MVC 2.0

    - by Diep-Vriezer
    I'm trying to validate a model containing other objects with validation rules using the System.ComponentModel.DataAnnotations attributes was hoping the default MVC implementation would suffice: var obj = js.Deserialize(json, objectInfo.ObjectType); if(!TryValidateModel(obj)) { // Handle failed model validation. } The object is composed of primitive types but also contains other classes which also use DataAnnotications. Like so: public class Entry { [Required] public Person Subscriber { get; set; } [Required] public String Company { get; set; } } public class Person { public String FirstName { get; set;} [Required] public String Surname { get; set; } } The problem is that the ASP.NET MVC validation only goes down 1 level and only evaluates the properties of the top level class, as can be read on digitallycreated.net/Blog/54/deep-inside-asp.net-mvc-2-model-metadata-and-validation. Does anyone know an elegant solution to this? I've tried xVal, but they seem to use a non-recursive pattern (http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/). Someone must have run into this problem before right? Nesting objects in your model doesn't seem so weird if you're designing a web service.

    Read the article

  • How to publish an ASP.NET MVC website

    - by Luke Puplett
    Hello -- I've a site that I'd like to publish to a co-located live server. I'm finding this simple task quite hard. My problems begin with the Web Deploy tool (1.1) giving me a 401 Unauthorized as the adminstrator because port :8172 comes up in the errors and this port is blocked - but the documentation says "The default ListenURL is http://+:80/MsDeployAgentService"! I'm loathe to open another port and I've little patience these days so I thought bu66er it, I'll create a Web Deploy package and import it into IIS on the server over RDP. I notice first that Visual Studio doesn't use a dialog box to gather settings, or use my Publish profiles but seems to use a tab in the project properties, although I think these are ignored when importing the package anyway? I'm now sitting in the import wizard with Application Path and Connection String. I've cleared the conn string as I think this is for some ASP stuff I don't use but when I enter nothing in the Application Path, the wizard barks at me saying that basically I'm a weirdo because most people publish to folders beneath the root site. Now, I want my site to be site.com/Home/About and not site.com/subfolder/Home/About and I think being an MVC routed site that a subfolder will introduce other headaches. Should I go ahead and use the root? Finally, I also want to publish a web service to www.site.com/services/soap which I think IIS can handle. While typing this question, Amazon have delivered my IIS 7 Resource Kit, and I've been scouring the internet but actually I'm getting more confused. Comment here seems to show consensus opinion that Publish isn't for production sites and that real men roll their own. http://stackoverflow.com/questions/260525/asp-net-website-publish-vs-web-deployment-project ...I guess this was pre- Web Deployment Tool era? I'm going to experiment on a spare box for now but any assistance is welcome. Luke

    Read the article

  • Top 5 reasons for using ASP.NET MVC 2 rather than ASP.NET MVC 1

    - by Richard Ev
    I've been using ASP.NET MVC 1 for a while now, and am keen to take advantage of the improvements in MVC 2. Things like validation seem greatly improved, and strongly-typed HTML helper methods look great. So, for those of you who have real-world practical experience of using ASP.NET MVC 1 and are now using MVC 2, what are your top 5 reasons for using MVC 2?

    Read the article

  • Using jQuery to POST Form Data to an ASP.NET ASMX AJAX Web Service

    - by Rick Strahl
    The other day I got a question about how to call an ASP.NET ASMX Web Service or PageMethods with the POST data from a Web Form (or any HTML form for that matter). The idea is that you should be able to call an endpoint URL, send it regular urlencoded POST data and then use Request.Form[] to retrieve the posted data as needed. My first reaction was that you can’t do it, because ASP.NET ASMX AJAX services (as well as Page Methods and WCF REST AJAX Services) require that the content POSTed to the server is posted as JSON and sent with an application/json or application/x-javascript content type. IOW, you can’t directly call an ASP.NET AJAX service with regular urlencoded data. Note that there are other ways to accomplish this. You can use ASP.NET MVC and a custom route, an HTTP Handler or separate ASPX page, or even a WCF REST service that’s configured to use non-JSON inputs. However if you want to use an ASP.NET AJAX service (or Page Methods) with a little bit of setup work it’s actually quite easy to capture all the form variables on the client and ship them up to the server. The basic steps needed to make this happen are: Capture form variables into an array on the client with jQuery’s .serializeArray() function Use $.ajax() or my ServiceProxy class to make an AJAX call to the server to send this array On the server create a custom type that matches the .serializeArray() name/value structure Create extension methods on NameValue[] to easily extract form variables Create a [WebMethod] that accepts this name/value type as an array (NameValue[]) This seems like a lot of work but realize that steps 3 and 4 are a one time setup step that can be reused in your entire site or multiple applications. Let’s look at a short example that looks like this as a base form of fields to ship to the server: The HTML for this form looks something like this: <div id="divMessage" class="errordisplay" style="display: none"> </div> <div> <div class="label">Name:</div> <div><asp:TextBox runat="server" ID="txtName" /></div> </div> <div> <div class="label">Company:</div> <div><asp:TextBox runat="server" ID="txtCompany"/></div> </div> <div> <div class="label" ></div> <div> <asp:DropDownList runat="server" ID="lstAttending"> <asp:ListItem Text="Attending" Value="Attending"/> <asp:ListItem Text="Not Attending" Value="NotAttending" /> <asp:ListItem Text="Maybe Attending" Value="MaybeAttending" /> <asp:ListItem Text="Not Sure Yet" Value="NotSureYet" /> </asp:DropDownList> </div> </div> <div> <div class="label">Special Needs:<br /> <small>(check all that apply)</small></div> <div> <asp:ListBox runat="server" ID="lstSpecialNeeds" SelectionMode="Multiple"> <asp:ListItem Text="Vegitarian" Value="Vegitarian" /> <asp:ListItem Text="Vegan" Value="Vegan" /> <asp:ListItem Text="Kosher" Value="Kosher" /> <asp:ListItem Text="Special Access" Value="SpecialAccess" /> <asp:ListItem Text="No Binder" Value="NoBinder" /> </asp:ListBox> </div> </div> <div> <div class="label"></div> <div> <asp:CheckBox ID="chkAdditionalGuests" Text="Additional Guests" runat="server" /> </div> </div> <hr /> <input type="button" id="btnSubmit" value="Send Registration" /> The form includes a few different kinds of form fields including a multi-selection listbox to demonstrate retrieving multiple values. Setting up the Server Side [WebMethod] The [WebMethod] on the server we’re going to call is going to be very simple and just capture the content of these values and echo then back as a formatted HTML string. Obviously this is overly simplistic but it serves to demonstrate the simple point of capturing the POST data on the server in an AJAX callback. public class PageMethodsService : System.Web.Services.WebService { [WebMethod] public string SendRegistration(NameValue[] formVars) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Thank you {0}, <br/><br/>", HttpUtility.HtmlEncode(formVars.Form("txtName"))); sb.AppendLine("You've entered the following: <hr/>"); foreach (NameValue nv in formVars) { // strip out ASP.NET form vars like _ViewState/_EventValidation if (!nv.name.StartsWith("__")) { if (nv.name.StartsWith("txt") || nv.name.StartsWith("lst") || nv.name.StartsWith("chk")) sb.Append(nv.name.Substring(3)); else sb.Append(nv.name); sb.AppendLine(": " + HttpUtility.HtmlEncode(nv.value) + "<br/>"); } } sb.AppendLine("<hr/>"); string[] needs = formVars.FormMultiple("lstSpecialNeeds"); if (needs == null) sb.AppendLine("No Special Needs"); else { sb.AppendLine("Special Needs: <br/>"); foreach (string need in needs) { sb.AppendLine("&nbsp;&nbsp;" + need + "<br/>"); } } return sb.ToString(); } } The key feature of this method is that it receives a custom type called NameValue[] which is an array of NameValue objects that map the structure that the jQuery .serializeArray() function generates. There are two custom types involved in this: The actual NameValue type and a NameValueExtensions class that defines a couple of extension methods for the NameValue[] array type to allow for single (.Form()) and multiple (.FormMultiple()) value retrieval by name. The NameValue class is as simple as this and simply maps the structure of the array elements of .serializeArray(): public class NameValue { public string name { get; set; } public string value { get; set; } } The extension method class defines the .Form() and .FormMultiple() methods to allow easy retrieval of form variables from the returned array: /// <summary> /// Simple NameValue class that maps name and value /// properties that can be used with jQuery's /// $.serializeArray() function and JSON requests /// </summary> public static class NameValueExtensionMethods { /// <summary> /// Retrieves a single form variable from the list of /// form variables stored /// </summary> /// <param name="formVars"></param> /// <param name="name">formvar to retrieve</param> /// <returns>value or string.Empty if not found</returns> public static string Form(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).FirstOrDefault(); if (matches != null) return matches.value; return string.Empty; } /// <summary> /// Retrieves multiple selection form variables from the list of /// form variables stored. /// </summary> /// <param name="formVars"></param> /// <param name="name">The name of the form var to retrieve</param> /// <returns>values as string[] or null if no match is found</returns> public static string[] FormMultiple(this NameValue[] formVars, string name) { var matches = formVars.Where(nv => nv.name.ToLower() == name.ToLower()).Select(nv => nv.value).ToArray(); if (matches.Length == 0) return null; return matches; } } Using these extension methods it’s easy to retrieve individual values from the array: string name = formVars.Form("txtName"); or multiple values: string[] needs = formVars.FormMultiple("lstSpecialNeeds"); if (needs != null) { // do something with matches } Using these functions in the SendRegistration method it’s easy to retrieve a few form variables directly (txtName and the multiple selections of lstSpecialNeeds) or to iterate over the whole list of values. Of course this is an overly simple example – in typical app you’d probably want to validate the input data and save it to the database and then return some sort of confirmation or possibly an updated data list back to the client. Since this is a full AJAX service callback realize that you don’t have to return simple string values – you can return any of the supported result types (which are most serializable types) including complex hierarchical objects and arrays that make sense to your client code. POSTing Form Variables from the Client to the AJAX Service To call the AJAX service method on the client is straight forward and requires only use of little native jQuery plus JSON serialization functionality. To start add jQuery and the json2.js library to your page: <script src="Scripts/jquery.min.js" type="text/javascript"></script> <script src="Scripts/json2.js" type="text/javascript"></script> json2.js can be found here (be sure to remove the first line from the file): http://www.json.org/json2.js It’s required to handle JSON serialization for those browsers that don’t support it natively. With those script references in the document let’s hookup the button click handler and call the service: $(document).ready(function () { $("#btnSubmit").click(sendRegistration); }); function sendRegistration() { var arForm = $("#form1").serializeArray(); $.ajax({ url: "PageMethodsService.asmx/SendRegistration", type: "POST", contentType: "application/json", data: JSON.stringify({ formVars: arForm }), dataType: "json", success: function (result) { var jEl = $("#divMessage"); jEl.html(result.d).fadeIn(1000); setTimeout(function () { jEl.fadeOut(1000) }, 5000); }, error: function (xhr, status) { alert("An error occurred: " + status); } }); } The key feature in this code is the $("#form1").serializeArray();  call which serializes all the form fields of form1 into an array. Each form var is represented as an object with a name/value property. This array is then serialized into JSON with: JSON.stringify({ formVars: arForm }) The format for the parameter list in AJAX service calls is an object with one property for each parameter of the method. In this case its a single parameter called formVars and we’re assigning the array of form variables to it. The URL to call on the server is the name of the Service (or ASPX Page for Page Methods) plus the name of the method to call. On return the success callback receives the result from the AJAX callback which in this case is the formatted string which is simply assigned to an element in the form and displayed. Remember the result type is whatever the method returns – it doesn’t have to be a string. Note that ASP.NET AJAX and WCF REST return JSON data as a wrapped object so the result has a ‘d’ property that holds the actual response: jEl.html(result.d).fadeIn(1000); Slightly simpler: Using ServiceProxy.js If you want things slightly cleaner you can use the ServiceProxy.js class I’ve mentioned here before. The ServiceProxy class handles a few things for calling ASP.NET and WCF services more cleanly: Automatic JSON encoding Automatic fix up of ‘d’ wrapper property Automatic Date conversion on the client Simplified error handling Reusable and abstracted To add the service proxy add: <script src="Scripts/ServiceProxy.js" type="text/javascript"></script> and then change the code to this slightly simpler version: <script type="text/javascript"> proxy = new ServiceProxy("PageMethodsService.asmx/"); $(document).ready(function () { $("#btnSubmit").click(sendRegistration); }); function sendRegistration() { var arForm = $("#form1").serializeArray(); proxy.invoke("SendRegistration", { formVars: arForm }, function (result) { var jEl = $("#divMessage"); jEl.html(result).fadeIn(1000); setTimeout(function () { jEl.fadeOut(1000) }, 5000); }, function (error) { alert(error.message); } ); } The code is not very different but it makes the call as simple as specifying the method to call, the parameters to pass and the actions to take on success and error. No more remembering which content type and data types to use and manually serializing to JSON. This code also removes the “d” property processing in the response and provides more consistent error handling in that the call always returns an error object regardless of a server error or a communication error unlike the native $.ajax() call. Either approach works and both are pretty easy. The ServiceProxy really pays off if you use lots of service calls and especially if you need to deal with date values returned from the server  on the client. Summary Making Web Service calls and getting POST data to the server is not always the best option – ASP.NET and WCF AJAX services are meant to work with data in objects. However, in some situations it’s simply easier to POST all the captured form data to the server instead of mapping all properties from the input fields to some sort of message object first. For this approach the above POST mechanism is useful as it puts the parsing of the data on the server and leaves the client code lean and mean. It’s even easy to build a custom model binder on the server that can map the array values to properties on an object generically with some relatively simple Reflection code and without having to manually map form vars to properties and do string conversions. Keep in mind though that other approaches also abound. ASP.NET MVC makes it pretty easy to create custom routes to data and the built in model binder makes it very easy to deal with inbound form POST data in its original urlencoded format. The West Wind West Wind Web Toolkit also includes functionality for AJAX callbacks using plain POST values. All that’s needed is a Method parameter to query/form value to specify the method to be called on the server. After that the content type is completely optional and up to the consumer. It’d be nice if the ASP.NET AJAX Service and WCF AJAX Services weren’t so tightly bound to the content type so that you could more easily create open access service endpoints that can take advantage of urlencoded data that is everywhere in existing pages. It would make it much easier to create basic REST endpoints without complicated service configuration. Ah one can dream! In the meantime I hope this article has given you some ideas on how you can transfer POST data from the client to the server using JSON – it might be useful in other scenarios beyond ASP.NET AJAX services as well. Additional Resources ServiceProxy.js A small JavaScript library that wraps $.ajax() to call ASP.NET AJAX and WCF AJAX Services. Includes date parsing extensions to the JSON object, a global dataFilter for processing dates on all jQuery JSON requests, provides cleanup for the .NET wrapped message format and handles errors in a consistent fashion. Making jQuery Calls to WCF/ASMX with a ServiceProxy Client More information on calling ASMX and WCF AJAX services with jQuery and some more background on ServiceProxy.js. Note the implementation has slightly changed since the article was written. ww.jquery.js The West Wind West Wind Web Toolkit also includes ServiceProxy.js in the West Wind jQuery extension library. This version is slightly different and includes embedded json encoding/decoding based on json2.js.© Rick Strahl, West Wind Technologies, 2005-2010Posted in jQuery  ASP.NET  AJAX  

    Read the article

  • New Bundling and Minification Support (ASP.NET 4.5 Series)

    - by ScottGu
    This is the sixth in a series of blog posts I'm doing on ASP.NET 4.5. The next release of .NET and Visual Studio include a ton of great new features and capabilities.  With ASP.NET 4.5 you'll see a bunch of really nice improvements with both Web Forms and MVC - as well as in the core ASP.NET base foundation that both are built upon. Today’s post covers some of the work we are doing to add built-in support for bundling and minification into ASP.NET - which makes it easy to improve the performance of applications.  This feature can be used by all ASP.NET applications, including both ASP.NET MVC and ASP.NET Web Forms solutions. Basics of Bundling and Minification As more and more people use mobile devices to surf the web, it is becoming increasingly important that the websites and apps we build perform well with them. We’ve all tried loading sites on our smartphones – only to eventually give up in frustration as it loads slowly over a slow cellular network.  If your site/app loads slowly like that, you are likely losing potential customers because of bad performance.  Even with powerful desktop machines, the load time of your site and perceived performance can make an enormous customer perception. Most websites today are made up of multiple JavaScript and CSS files to separate the concerns and keep the code base tight. While this is a good practice from a coding point of view, it often has some unfortunate consequences for the overall performance of the website.  Multiple JavaScript and CSS files require multiple HTTP requests from a browser – which in turn can slow down the performance load time.  Simple Example Below I’ve opened a local website in IE9 and recorded the network traffic using IE’s built-in F12 developer tools. As shown below, the website consists of 5 CSS and 4 JavaScript files which the browser has to download. Each file is currently requested separately by the browser and returned by the server, and the process can take a significant amount of time proportional to the number of files in question. Bundling ASP.NET is adding a feature that makes it easy to “bundle” or “combine” multiple CSS and JavaScript files into fewer HTTP requests. This causes the browser to request a lot fewer files and in turn reduces the time it takes to fetch them.   Below is an updated version of the above sample that takes advantage of this new bundling functionality (making only one request for the JavaScript and one request for the CSS): The browser now has to send fewer requests to the server. The content of the individual files have been bundled/combined into the same response, but the content of the files remains the same - so the overall file size is exactly the same as before the bundling.   But notice how even on a local dev machine (where the network latency between the browser and server is minimal), the act of bundling the CSS and JavaScript files together still manages to reduce the overall page load time by almost 20%.  Over a slow network the performance improvement would be even better. Minification The next release of ASP.NET is also adding a new feature that makes it easy to reduce or “minify” the download size of the content as well.  This is a process that removes whitespace, comments and other unneeded characters from both CSS and JavaScript. The result is smaller files, which will download and load in a browser faster.  The graph below shows the performance gain we are seeing when both bundling and minification are used together: Even on my local dev box (where the network latency is minimal), we now have a 40% performance improvement from where we originally started.  On slow networks (and especially with international customers), the gains would be even more significant. Using Bundling and Minification inside ASP.NET The upcoming release of ASP.NET makes it really easy to take advantage of bundling and minification within projects and see performance gains like in the scenario above. The way it does this allows you to avoid having to run custom tools as part of your build process –  instead ASP.NET has added runtime support to perform the bundling/minification for you dynamically (caching the results to make sure perf is great).  This enables a really clean development experience and makes it super easy to start to take advantage of these new features. Let’s assume that we have a simple project that has 4 JavaScript files and 6 CSS files: Bundling and Minifying the .css files Let’s say you wanted to reference all of the stylesheets in the “Styles” folder above on a page.  Today you’d have to add multiple CSS references to get all of them – which would translate into 6 separate HTTP requests: The new bundling/minification feature now allows you to instead bundle and minify all of the .css files in the Styles folder – simply by sending a URL request to the folder (in this case “styles”) with an appended “/css” path after it.  For example:    This will cause ASP.NET to scan the directory, bundle and minify the .css files within it, and send back a single HTTP response with all of the CSS content to the browser.  You don’t need to run any tools or pre-processor to get this behavior.  This enables you to cleanly separate your CSS into separate logical .css files and maintain a very clean development experience – while not taking a performance hit at runtime for doing so.  The Visual Studio designer will also honor the new bundling/minification logic as well – so you’ll still get a WYSWIYG designer experience inside VS as well. Bundling and Minifying the JavaScript files Like the CSS approach above, if we wanted to bundle and minify all of our JavaScript into a single response we could send a URL request to the folder (in this case “scripts”) with an appended “/js” path after it:   This will cause ASP.NET to scan the directory, bundle and minify the .js files within it, and send back a single HTTP response with all of the JavaScript content to the browser.  Again – no custom tools or builds steps were required in order to get this behavior.  And it works with all browsers. Ordering of Files within a Bundle By default, when files are bundled by ASP.NET they are sorted alphabetically first, just like they are shown in Solution Explorer. Then they are automatically shifted around so that known libraries and their custom extensions such as jQuery, MooTools and Dojo are loaded before anything else. So the default order for the merged bundling of the Scripts folder as shown above will be: Jquery-1.6.2.js Jquery-ui.js Jquery.tools.js a.js By default, CSS files are also sorted alphabetically and then shifted around so that reset.css and normalize.css (if they are there) will go before any other file. So the default sorting of the bundling of the Styles folder as shown above will be: reset.css content.css forms.css globals.css menu.css styles.css The sorting is fully customizable, though, and can easily be changed to accommodate most use cases and any common naming pattern you prefer.  The goal with the out of the box experience, though, is to have smart defaults that you can just use and be successful with. Any number of directories/sub-directories supported In the example above we just had a single “Scripts” and “Styles” folder for our application.  This works for some application types (e.g. single page applications).  Often, though, you’ll want to have multiple CSS/JS bundles within your application – for example: a “common” bundle that has core JS and CSS files that all pages use, and then page specific or section specific files that are not used globally. You can use the bundling/minification support across any number of directories or sub-directories in your project – this makes it easy to structure your code so as to maximize the bunding/minification benefits.  Each directory by default can be accessed as a separate URL addressable bundle.  Bundling/Minification Extensibility ASP.NET’s bundling and minification support is built with extensibility in mind and every part of the process can be extended or replaced. Custom Rules In addition to enabling the out of the box - directory-based - bundling approach, ASP.NET also supports the ability to register custom bundles using a new programmatic API we are exposing.  The below code demonstrates how you can register a “customscript” bundle using code within an application’s Global.asax class.  The API allows you to add/remove/filter files that go into the bundle on a very granular level:     The above custom bundle can then be referenced anywhere within the application using the below <script> reference:     Custom Processing You can also override the default CSS and JavaScript bundles to support your own custom processing of the bundled files (for example: custom minification rules, support for Saas, LESS or Coffeescript syntax, etc). In the example below we are indicating that we want to replace the built-in minification transforms with a custom MyJsTransform and MyCssTransform class. They both subclass the CSS and JavaScript minifier respectively and can add extra functionality:     The end result of this extensibility is that you can plug-into the bundling/minification logic at a deep level and do some pretty cool things with it. 2 Minute Video of Bundling and Minification in Action Mads Kristensen has a great 90 second video that shows off using the new Bundling and Minification feature.  You can watch the 90 second video here. Summary The new bundling and minification support within the next release of ASP.NET will make it easier to build fast web applications.  It is really easy to use, and doesn’t require major changes to your existing dev workflow.  It is also supports a rich extensibility API that enables you to customize it however you want. You can easily take advantage of this new support within ASP.NET MVC, ASP.NET Web Forms and ASP.NET Web Pages based applications. Hope this helps, Scott P.S. In addition to blogging, I use Twitter to-do quick posts and share links. My Twitter handle is: @scottgu

    Read the article

  • Is ASP.NET MVC completely (and exclusively) based on conventions?

    - by Mike Valeriano
    --TL;DR Is there a "Hello World!" ASP.NET MVC tutorial out there that doesn't rely on conventions and "stock" projects? Is it even possible to take advantage of the technology without reusing the default file structure, and start from a single "hello_world.asp" file or something (like in PHP)? Am I completely mistaken and I should be looking somewhere else, maybe this? I'm interested in the MVC framework, not Web Forms --Background I've played a bit with PHP in the past, just for fun, and now I'm back to it since web development became relevant for me once again. I'm no professional, but I try to gain as much knowledge and control over the technology I'm working with as possible. I'm using Visual Studio 2012 for C# - my "desktop" language of choice - and since I got the Professional Edition from Dreamspark, the Web Development Tools are available, including ASP.NET MVC 4. I won't touch Web Forms, but the MVC Framework got my attention because the MVC pattern is something I can really relate to, since it provides the control I want but... not quite. Learning PHP was easy - and right form the start I could just create a "hello_world.php" file and just do something like this for immediate results: <!-- file: hello_world.php --> <?php> echo "Hello World!"; <?> But I couldn't find a single ASP.NET (MVC) tutorial out there (I'll be sure to buy one of the upcoming MVC 4 books, only a month away or so) that would start like that. They all start with a sample project, building up knowledge from the basics and heavily using conventions as they go along. Which is fine, I suppose, but it's now the best way for me to learn things. Even the "Empty" project template for a new ASP.NET MVC 4 Application in VS2012 is not empty at all: several files and folders are created for you - much like a new C# desktop application project, but with C# I can in fact start from scratch, creating the project structure myself. It is not the case with PHP: I can choose from a plethora of different MVC frameworks I can just create my own framework I can just skip frameworks altogether, and toss random PHP along with my HTML on a single file and make it work I understand the framework needs to establish some rules, but what if I just want to create a single page website with some C# logic behind it? Do I really need to create a whole bloat of files and folders for the sake of convention? Also, please understand that I haven't gotten far on any of those tutorials mainly because of this reason, but, if that's the only way to do it, I'll go for it using one of the books I've mentioned before. This is my first contact with ASP.NET but from the few comparisons I've read, I believe I should stay the hell away from Web Forms. Thank you. (Please forgive the broken English - it is not my primary language.)

    Read the article

  • How to create Ror style Restful routing in Asp.net MVC Web Api

    - by Jas
    How to configure routing in asp.net web api, to that I can code for the following actions in my ApiController inherited class? |======================================================================================| |Http Verb| Path | Action | Used for | |======================================================================================| | GET | /photos | index | display a list of all photos | | GET | /photos/new | new | return an HTML form for creating a new photo | | POST | /photos/ | create | create a new photo | | GET | /photos/:id | show | display a specific photo | | GET | /photos/:id/edit | edit | return an HTML form for editing a photo | | PUT | /photos/:id | update | update a specific photo | | DELETE | /photos/:id | destroy | delete a specific photo |

    Read the article

  • asp.net mvc url routing

    - by progtick
    How do I map something like domain.com/username? The problem is I think that the MVC routing looks for the controller to determine how it should handle the mapping request. I am pretty new to ASP.NET MVC. However, based on the tutorials so far, the routing mechanism seems rather rigid.

    Read the article

  • showing errors from actions in table-based views

    - by enashnash
    I have a view where I want to perform different actions on the items in each row in a table, similar to this (in, say, ~/Views/Thing/Manage.aspx): <table> <% foreach (thing in Model) { %> <tr> <td><%: thing.x %></td> <td> <% using (Html.BeginForm("SetEnabled", "Thing")) { %> <%: Html.Hidden("x", thing.x) %> <%: Html.Hidden("enable", !thing.Enabled) %> <input type="submit" value="<%: thing.Enabled ? "Disable" : "Enable" %>" /> <% } %> </td> <!-- more tds with similar action forms here, a few per table row --> </tr> <% } %> In my ThingController, I have functions similar to the following: public ActionResult Manage() { return View(ThingService.GetThings()); } [HttpPost] public ActionResult SetEnabled(string x, bool enable) { try { ThingService.SetEnabled(x, enable); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); // I know this is wrong... } return RedirectToAction("Manage"); } In the most part, this is working fine. The problem is that if ThingService.SetEnabled throws an error, I want to be able to display the error at the top of the table. I've tried a few things with Html.ValidationSummary() in the page but I can't get it to work. Note that I don't want to send the user to a separate page to do this, and I'm trying to do it without using any javascript. Am I going about displaying my table in the best way? How do I get the errors displayed in the way I want them to? I will end up with perhaps 40 small forms on the page. This approach comes largely from this article, but it doesn't handle the errors in the way I need to. Any takers?

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >