I've never used AJAX and am, quite frankly, not much versed in JS either.
I have a page (Product Browser) that has the following breakdown:
- Navigation (First, Prev, 1, 2, 3 Next, Last) - full post back
- Items per Page drop down - I want to AJAX this
- Left Column - Filters - I want to AJAX this
- Product Display area - displays products based on 1, 2 & 3 above
I am starting with Item #2 and am trying to figure out how to change item 4 based off of the OnChange event for the drop down. I am at a loss as to where. or how, to start. Should it be AJAX? JQuery? A combination of both? And remember - it is in a MVC based app.
TIA
-
You can try this simple demo from my blog
-
AJAX is just a request pulling information from a page without refreshing the browser. You can use ASP.NET AJAX or JQuery's AJAX and you should get the same results.
And JQuery is just a library to select and manipulate the DOM. JQuery has a few AJAX functions you can use as well but JQuery can be used for much much more.
I don't know how ASP's version works exactly but AJAX is just a page request.
-
I would definately check out jQuery and not bother with MS's ajax implementation. For the things you want, you can check out jQuery's docs for $post for example or ajax/load functions.
You can either add events to the controls on your page, like the carpets / area rugs radio buttons, or add that event to the submit button and then make a call to the products controller to retrieve a partial view that loads into the products div.
-
The answer to your question is definitely, "yes".
I've got one in front of me right now, so I'll try to abstract it out.
First, create a controller action that returns a JsonResult (rather than ActionResult). Other than its return type it's just like any other action, so you can send parameters, etc. The only thing that's really different is that you're going to return a JsonResult() object, setting its Data property and any other properties that you may need. Mine looks something like this (very pseudo-codish...):
public JsonResult GetList(int parentId) { var results = dataRepository.GetById(parentId); return new JsonResult() { Data = results.ToArray(); }; }Now, in your view, create a script that looks something like this. Note that this is jQuery syntax, so it may look a bit unusual if you're not familiar with it.
<script language="javascript" type="text/javascript"> // When the document is ready, start firing our AJAX $(document).ready(function() { // Bind a function to the "change" event of our drop-down list $("#dropDownId").bind("change", function(e) { updateList(); }); } var retrieveData = function(path, parentId, fnHandleCallback) { // Use the getJSON method to call our JsonResult action $.getJSON(path, { parentId: parentId }, function(data) { fnHandleCallback(data); }); }; // The path parameter is our JSON controller action function updateList() { retrieveData("/Controller/GetList", $("#dropDownId").val(), handleResponse); } function handleResponse(data) { // Ok, now we have the JSON data, we need to do something with it. I'm adding it to another dropdown. $("#otherDropDownId > option").remove(); for (d in data) { var item = data[d]; $("#otherDropDownId").append("<option value=\"" + item.Value + "\">" + item.Text + "</option>"); } } </script> <%= Html.DropDownList("dropDownId", new SelectList(new List<SelectListItem>())) %> <%= Html.DropDownList("otherDropDownId", new SelectList(new List<SelectListItem>())) %>This is all very much off the top of my head, so let me know if something needs to be clarified or corrected.
Edit
As noted in my comment, in order to "AJAXify" your page, you don't really want to push everything around in your Model. Instead, it sounds like you want something like this:
Controller action:
public JsonResult GetPagedData(int page, int itemsPerPage, string[] filters) { var results = dataRepository.GetPagedItems(pageId, itemsPerPage, filters); return new JsonResult() { Data = results.ToArray(); }; }JS changes:
var retrieveData = function(path, pageNumber, pageSize, filters, fnHandleCallback) { // Use the getJSON method to call our JsonResult action $.getJSON(path, { page: pageNumber, itemsPerPage: pageSize, filters: filters }, function(data) { fnHandleCallback(data); }); }; // The path parameter is our JSON controller action function updateList() { retrieveData("/Controller/GetPagedData", $("#pageNumber").val(), $("#dropDownId").val(), null, handleResponse); }I've intentionally ignored figuring out both the page number and the filters - they would follow essentially the same principles.
Finally, when you're rendering the data you'll put it into your product grid rather than another drop-down.
How to add Stroke to Text in AS3?
I am coding in AS3 and want to add a stroke to text that I'm displaying to the screen. My current code is:
format = new TextFormat("BN Elements", 14, 0xEEEEEE, false, false, false, null, null, "left");
format.font = "BN Elements"
scoreText = initText(starsleftText, format, "", 160,5, 545, 61);
scoreText = "Stroke This Text";
As the text is dynamically generated I can't create it as a text object in the Flash IDE - where I know to add a stroke I can use the "glow" function set to 1000% and Low quality.
I suppose my question is, how can I apply the "glow" filter effect with similar properties within AS3 directly? Or is there an alternative "stroke" function I don't know about?
-
It's pretty easy:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/filters/GlowFilter.html (There's an example at the bottom of the page)
I'm not sure if they've added anything new as far as adding a real stroke, but the glow filter 'stroke' works just as well with code.
You could also create a pixel bender filter that would give you a bit more control over the effect, I can't seem to find any already written ones out there though:(
quoo : oh also, beware, if the text is selectable, using the glow filter will add a stroke to the selection as well. -
Flash generates its strokes from the edges of shapes. Since you are using text dynamically (not in authoring) Flash can render with either 1) device text which in drawn by the operating system, or 2) embedded text in your SWF file. In the first case, Flash doesn't (currently) have access to the edges to stroke them. In the 2nd, Flash uses a specialized sub-renderer for text that (again currently) doesn't support stroking, or for that matter, anything but solid color fills.
Short answer: stroking of text currently isn't supported in the runtime, although the glow or pixel bender approach suggested is a good idea.
SQL Server- ORDER BY CASE problem
I have the following the query running dynamically
SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = 'na' then 0 else 1 end, Make , Model, Year DESC
This is returning the following error:
Error Executing Database Query. [Macromedia][SQLServer JDBC Driver][SQLServer]Incorrect syntax near 'na'.
Thanks in advanced for your help
-
Try enclosing the
casestatement in parentheses.SELECT * FROM Vehicles WHERE (DKID IN (69954)) ORDER BY (case when ImageName1 = 'na' then 0 else 1 end), Make , Model, Year DESC -
works for me
here is repo script
use tempdb go create table Vehicles(DKID int,ImageName1 varchar(50), Make int, Model int, Year int) insert Vehicles values (69954,'na',1,1,2007) insert Vehicles values(69954,'bla',1,1,2008) go SELECT * FROM Vehicles WHERE (DKID IN (69954)) ORDER BY case when ImageName1 = 'na' then 0 else 1 end, Make , Model, Year DESC -
are you running this query dynamically?, if so you might need to escape the quotes around 'na':
SELECT * FROM Vehicles WHERE (DKID IN (69954)) ORDER BY case when ImageName1 = ''na'' then 0 else 1 end, Make , Model, Year DESCPatcouch22 : I am running it dynamically, however the escape quotes still provide the same error.KM : try replacing 'na' with char(110)+char(97), which will be slow, but will help diagnose it more...Patcouch22 : that did allow it to run...KM : that shows that you are not escaping it properly, is "na" a constant or part of the dynamic query? edit your question to show that is generating the query, the propblem is there. -
Your query works fine for me in SQL Mgmt Studio... Maybe try it this way instead to see if it gets you anywhere:
SELECT case when ImageName1 = 'na' then 0 else 1 end as OrderCol, * FROM Vehicles WHERE (DKID IN (69954)) ORDER BY OrderCol,Make,Model,Year DESC -
You're using JDBC. Is there probably a transformation / interpretation from JDBC? Try making the 'na' a parameter. Check if there is a certain syntax in JDBC for string constants in queries. I don't use JDBC, so I could be completely wrong.
-
As KMike said, it looks like you didn't not escape properly.
Basically, when you ran your statement, it did not generate a syntactically correct SQL statement from the dynamic SQL.
Generally, when I am writing dynamic sql, I use a print statement to print the generated SQL. I can then review the generated sql visually for obvious mistakes, and then execute it it to make sure it works as expected.
If I made a mistake in the dynamic SQL, it will usually be revealed here.
How do you make your Java application memory efficient?
How do you optimize the heap size usage of an application that has a lot (millions) of long-lived objects? (big cache, loading lots of records from a db)
- Use the right data type
- Avoid java.lang.String to represent other data types
- Avoid duplicated objects
- Use enums if the values are known in advance
- Use object pools
- String.intern() (good idea?)
- Load/keep only the objects you need
I am looking for general programming or Java specific answers. No funky compiler switch.
Edit:
Optimize the memory representation of a POJO that can appear millions of times in the heap.
Use cases
- Load a huge csv file in memory (converted into POJOs)
- Use hibernate to retrieve million of records from a database
Resume of answers:
- Use flyweight pattern
- Copy on write
- Instead of loading 10M objects with 3 properties, is it more efficient to have 3 arrays (or other data structure) of size 10M? (Could be a pain to manipulate data but if you are really short on memory...)
-
You don't say what sort of objects you're looking to store, so it's a little difficult to offer detailed advice. However some (not exclusive) approaches, in no particular order, are:
- Use a flyweight pattern wherever possible.
- Caching to disc. There are numerous cache solutions for Java.
- There is some debate as to whether String.intern is a good idea. See here for a question re. String.intern(), and the amount of debate around its suitability.
- Make use of soft or weak references to store data that you can recreate/reload on demand. See here for how to use soft references with caching techniques.
Knowing more about the internals and lifetime of the objects you're storing would result in a more detailed answer.
-
I suggest you use a memory profiler, see where the memory is being consumed and optimise that. Without quantitative information you could end up changing thing which either have no effect or actually make things worse.
You could look at changing the representation of your data, esp if your objects are small. For example, you could represent a table of data as a series of columns with object arrays for each column, rather than one object per row. This can save a significant amount of overhead for each object if you don't need to represent an individual row. e.g. a table with 12 columns and 10,000,000 rows could use 12 objects (one per column) rather than 10 million (one per row)
Boune : Good trick for minimizing the number of objects.Boune : I agree that a memory profiler is a good starting point for someone who does not know which Class instances are taking all the memory. The question is more, if I know in advance I will have 10M pojo#1 in memory, how do minimize the consumption of each instance? -
Ensure good normalization of your object model, don't duplicate values.
Ahem, and, if it's only millions of objects I think I'd just go for a decent 64 bit VM and lots of ram ;)
Brian Agnew : Which is quite possibly the most cost-effective solution :-)duffymo : +1 - That's cutting to the heart of the issue.Fortyrunner : Great answer. Using caches of data and reducing duplicate records and fields is a major saver.Boune : How do you minimize the number of duplicated values? Original question mentions usage of Enum, String.intern, object pools. How would you insure that values are not duplicated?krosenvold : @Boune There may be combinations (subsets) of values that are duplicate. -
I want to add something to the point Peter alredy made(can't comment on his answer :() it's always better to use a memory profiler(check java memory profiler) than to go by intution.80% of time it's routine that we ignore has some problem in it.also collection classes are more prone to memory leaks.
-
Normal "profilers" won't help you much, because you need an overview of all your "live" objects. You need heap dump analyzer. I recommend the Eclipse Memory analyzer.
Check for duplicated objects, starting with Strings. Check whether you can apply patterns like flightweight, copyonwrite, lazy initialization (google will be your friend).
-
You could just store fewer objects in memory. :) Use a cache that spills to disk or use Terracotta to cluster your heap (which is virtual) allowing unused parts to be flushed out of memory and transparently faulted back in.
-
A fancy one: keep most data compressed in ram. Only expand the current working set. If your data has good locality that can work nicely.
Use better data structures. The standard collections in java are rather memory intensive.
[what is a better data structure]
- If you take a look at the source for the collections, you'll see that if you restrict yourself in how you access the collection, you can save space per element.
- The way the collection handle growing is no good for large collections. Too much copying. For large collections, you need some block-based algorithm, like btree.
Boune : How would you define better data structures? How would you implement that? -
Spend some time getting acquainted with and tuning the VM command line options, especially those concerning garbage collection. While this won't change the memory used by your objects, it can have a big impact on performance with memory-intensive apps on machines with a lot of RAM.
-
If you have millions of Integers and Floats etc. then see if your algorithms allow for representing the data in arrays of primitives. That means fewer references and lower CPU cost of each garbage collection.
-
Assign nullvalue to all thevariableswhich areno longerused. Thusmake it available for Garbage collection.De-reference the collectionsonce usage is over, otherwise GC won't sweep those.
Boune : I disagree with item 1. I would just let the gc do what it is suppose to do. There are only a few cases (arrays, collections) where this could be useful, not all variables. http://stackoverflow.com/questions/449409/does-assigning-objects-to-null-in-java-impact-garbage-collection
.htaccess redirect after replace a word?
Hello, I need to use .htaccess file to replace a world in URL
something like this:
example URL: http://example.com/oldword/test-page.html
redirect to: http://example.com/newword/test-page.html
how can I use mod_rewrite to redirect every URL containt "/oldword/" to the same URL after replacing that word?
-
This should do it for you:
RewriteRule ^oldword/(.*) /newword/$1 [L]Edit: It might not work exactly depending on your RewriteBase settings, but it'll be close.
Second Edit: If you need to have a 301 Moved Permanently header associated with the old URLs, you can do something like this as well:
RewriteRule ^oldword/(.*) /newword/$1 [R=301,L] -
Hi,
see here:
<IfModule mod_rewrite.c> RewriteEngine on RewriteBase / RewriteRule ^oldword(.*)$ http://%{HTTP_HOST}/newword$1 [L] </IfModule>ciao,
Chris
Gumbo : It’s better to leave the protocol, host and port part away like zombat did. Additionally your rule would also redirect `/oldword-and-some-more` to `/newword-and-some-more` and I don’t think that’s what chiaf wanted.
windows user domain account question
Hi
I have one question regarding domain account. I have one domain controller where all the user information are stored. I have joined the domain on my laptop but I observed that I am able to log-in using domain credentials even if domain controller is down. How is this possible?
Kind Regards PK
-
You're using cached credentials. You can disable this in the registry if you want.
-
If you've logged on to the laptop prior to the Domain Controller being down, your credentials are cached locally on the machine.
This occurs so that you can use your domain credentials to log into the machine even if you are disconnected from the network (working from home, etc.).
-
Windows will cache previous user login credentials locally so you can still log in if the DC is down. You shouldn't be able to access network resources that might need you to login though.
Simple inter-proccess communication in Qt4
I need to make so that my application can have only one instance running at a time. Also when it's launched with a command line parameter ( like when registered to open certain file types ) it should pass the parameter to an existing instance and quit immediately without displaying graphical interface. You all probably know what I mean. The framework used is Qt 4, and it seems like it must have some facilities for that. Any ideas?
-
There is a Qt Solutions project doing this:
-
It's also possible to implement a this sort of class oneself using QSharedMemory (see QSharedMemory::attach() ). It's capable of being used for both determining whether other instance is already running and communicating/sending messages. Except some pointer magic and memory copying it's quite straightforward.
-
There are several ways to do inter process communication. Examples can be found in Qt's examples section.
<% foreach(RoomsAlive.Models.ProductDetail myRecord in Model.ProductDetail) { %>-
">
<%= myRecord.ProductSeriesName %> - <%= myRecord.ProductName %>
MSRP: $<%= myRecord.SKU_BasePrice %>
[Label] in <%= myRecord.ProductTypeName %>
Product Description: <%= myRecord.ProductDescription %>
Product Series Description: <%= myRecord.ProductSeriesDescription %>