I'm fiddling around with knockout js and trying to make a grid with a select in it.
It looks i'm a bit stuck here.
I would like to bind an array to the selectbox gridrow and after clicking the save (S) i would like to see an json response like
{ id: 2, name: "Long Cloak", price: "120.20", selthis: 1 }
here's what i got http://jsfiddle.net/marsmania00/JS6An/
any help would be appreciated!
regards,
michael
You were binding the list of options to the wrong level. the list of options is in $root.pulldown for your use case. See http://jsfiddle.net/JS6An/2/
Related
I've an ASP.Net MVC3 web app been using jQuery Form Plugin for ajaxSubmit. I've a grid and I use ajax postback to refresh it while filtering, sorting & paging - in simple words I just replace the grid html result I get from ajax postback. Works great for any kind of grid features because grid html is rendered on server side.
Now, I'm looking for a json based Grid with some basic features like sorting, paging and if possible grouping & server side paging! Editable Grid is not the main focus but it'll be an added advantage. I see most of the solutions would point towards Knockoutjs. I've been trying it out but it needs more homework esp for advance features like grouping, etc...
I've found some basic examples like
Knockoutjs basic grid (with add/delete)
The SimpleGrid component
jQgrid also supports json
jqxgrid
Along with that I also came across a new concept - JsonML + Browser-Side Templating (JBST) Basically, it works on json and before adding the elements to the page it allows us to alter the element's behavior. Browser side templating. Has anyone experienced it? Is it comparable to KO ?
I welcome suggestions and your expertise advice for my simple featured json based grid (assuming json would be the best way of passing the data). If you know another approach, do share it as well.
Have you checked out KoGrid, its a native KO grid
https://github.com/Knockout-Contrib/KoGrid
I did my homework and here's my final conclusion. To begin with - there's nothing like KO support - there has to be a ko binding handler for the plugin (except fo KOGrid).
DataTables - supports json but couldn't find native KO support (external plugin). Binding looks simple and straight fwd yet many diff script files.
SlickGrid - supports json but needs a bit post processing. Possible external KO binding feasible. Using ko.utils.unwrapObservable.
ko.SimpleGrid Implementation of binding ko.bindingHandlers.simpleGrid (supports paging) As seen in KO demo.(source) No native support for sorting but can be extended
My final choice -
KOGrid Probably the first pure KO based Grid! So obviously json compatible. Supports sorting natively (no extra scripting
needed). Also found server side paging for large data set. All in one!
function columnDefsVM() {
var self = this;
this.myData = ko.observableArray([{ name: "Moroni", age: 50 },
{ name: "Tiancum", age: 43 },
{ name: "Enos", age: 34 }]);
this.gridOptions = { data: self.myData,
columnDefs: [{field: 'name', displayName: 'Name'},{field: 'age', displayName: 'Age'}]
};
}
ko.applyBindings(new columnDefsVM());
Some others -
JsonML + Browser-Side Templating (JBST) couldn't infer too deep but it does pose an effective approach to use js for templating and runtime behavior modification!
Simple http://paramquery.com/demos
Feature rich jqGrid http://www.trirand.net/demoaspnetmvc.aspx (json & KO)
You might also take a look at the Grid samples here: jqxGrid with Knockout
Just a heads-up, I'm a total beginner as far as ajax is concerned and am just trying to find my way around it, so please bear with me :)
I have a View with a combo box in it (generated through a collection_select) and I display some data on the side of that form that essentially gives more details about the user's choice.
What I'd like to achieve is to be able to change that description on the side as soon as the customer makes a different selection in the combo. Basically, figure out what the current choice is, request data from the model, display returned data on the screen.
What's the simplest / most elegant way of achieving that? I think understanding the process would be a good launching ramp into the rest of the async View world for me.
Thanks!
I don't think ajax is necessary in this situation. Simply preload all the description values and store them in hidden divs:
<div class="description" id="choice1">
description for choice1 ...
</div>
...
Then hide them all:
// somewhere in your stylesheet
div.description {
display: none;
}
And finally on client side, bind to wanted events of the combo box:
// checkout documentation for other events, like select
$('some_id').change(function(data){
$('div.description').css('display', 'none');
var id = // get information about selected choice and figure out the id of description
$('div.description#' + id).css('display', 'block');
});
Chekout documentation for exact details but the main idea should be clear. In this way, you'll save yourself some unnecessary requests to your server.
So I found some great info on Autocomplete for Rails 3, it looks really easy to use. But I have a use case that doesnt fit and I need some advice.
I want to give the user the ability to add Products and Services to an Invoice through a simple form. I'd like them to be able to type into the Item field and have it autocomplete from both Product.name and Service.name as a single set.
I'm thinking of trying to write a parent model that overlays all three, but I still don't think that solves my problem since I can't use a function in the autocomplete definition from what I understand.
Any advice on how I might try to accomplish this? Even with the simple search examples that are out there they seem to be restricted to a single model.
If you're not opposed to introducing Redis into the mix, have a look at https://github.com/seatgeek/soulmate -- From the README:
Soulmate is a tool to help solve the common problem of developing a fast autocomplete feature. It uses Redis's sorted sets to build an index of partially completed words and the corresponding top matching items, and provides a simple sinatra app to query them. Soulmate finishes your sentences.
Soulmate was designed to be simple and fast, and offers the following:
Provide suggestions for multiple types of items in a single query (at SeatGeek we're autocompleting for performers, events, and venues)
Results are ordered by a user-specified score
Arbitrary metadata for each item (at SeatGeek we're storing both a url and a subtitle)
An item is a simple JSON object that looks like:
{
"id": 3,
"term": "Citi Field",
"score": 81,
"data": {
"url": "/citi-field-tickets/",
"subtitle": "Flushing, NY"
}
}
Where id is a unique identifier (within the specific type), term is the phrase you wish to provide completions for, score is a user-specified ranking metric (redis will order things lexicographically for items with the same score), and data is an optional container for metadata you'd like to return when this item is matched (at SeatGeek we're including a url for the item as well as a subtitle for when we present it in an autocomplete dropdown).
See Soulmate in action at SeatGeek.
If nothing else, maybe it'll give you some ideas on how to structure the data in a way that makes sense.
I did not write or have anything to do with soulmate. It's just a library I discovered when trying to solve a similar problem. Hope it helps!
If client-side autocomplete is an option (e.g. you have few products and services), you could go with JQuery autocomplete:
controller:
#keys = #categories.map { |x| x.name } + #entries.map { |x| x.description }
#autocomplete_categories = #keys.to_json.html_safe
view:
<script type="text/javascript">
$(document).ready(function() {
var data = <%= #autocomplete_categories %>;
$("#auto").autocomplete( { source: data } );
});
</script>
<input type="text" name="auto" id="auto" />
We are using Struts 2 and want a jQuery Grid showing a list of accounts. When a user clicks an account we want to take them to a page specific to that account.
At this point I'm looking for suggestions as to the best way to do this. Currently I'm building a URL server side which I then return but this isn't optimal since I don't have access to <s:url>.
One idea I've had is to combine <s:url> and each row Id on the client side but I haven't found a way to do this. Is there a grid would that allow this? or a better way?
Updated Explanation Attempt:
I am returning a json list to jQuery grid. One column in the grid is a url but I can't build that in the service level. Instead I'd love to have a way to use <s:url> when my json results are returned. Is there anyway to do this?
You cannot use <s:url> client side.
The Struts2-Tags get used serverside
to generate the HTML, so there's
basically no difference if you
construct them yourself or let JSP
construct the HTML.
There's the struts2-jQuery Plugin and with it the jQuery grid plugin. Find out more about it here:
https://code.google.com/p/struts2-jquery/
If you know the actionName and have the ID in the list you're iterating over, you can just code the necessary link yourself (if the object in the list has a getter named getId()):
<a href="http://host:port/webapp/actionName?id=<s:property value='id' />">
Hope that helps, if not please show the code of the page and / or dredefine your question.
There isn't a really straight forward way. Here is the answer to "Struts2 URL buiilding in action for JSON" answered on the struts mailing list:
http://old.nabble.com/Struts2-URL-building-in-action-for-JSON.-td30487914.html
If you get a chance let me know how you implement this.
I need to be able to edit a table of data in the browser.
I have seen in MVCContrib there is a HTML helper to render out a table. Useful... but what about if I want the user to be able to edit that table? From what I can see it does not help there.
What is the best way to approach this?
Traditional FORM with a TABLE inside? If so is MVC smart enough to parse the posted data back into a collection of rows? How would that work anyway?
Or perhaps it should just switch to edit mode when a row is clicked (using javascript etc) then when user moves to a different row an AJAX action is called to submit just the one row. I can imagine the logic could get complex here - this would presumably still use a form but would I have to insert it into the DOM dynamically?
I also need to be able to add rows to this table. I do not require paging support.
Is there an off the shelf solution out there?
Should I go back to web forms? :)
Take a look at Phil Haack's blog where he describes how to model bind to a list.
Maybe this can help?
I've got the same problem, and I have found a solution for it. Don't think it's the most beautiful, but it's ideal for me, because one of my requirements was be able to edit table data using jQuery's Jeditable plugin.
So I generate a table using MVCContrib's Grid<> extension:
Html.Grid<Somenamespace.Line>( Model.InvoiceLines )
.Attributes( id => "InvoiceGrid" )
.Columns( column => {
column.For( li => li.LineItem.ItemDescription ).Attributes( name => ".LineItem.ItemDescription", #class => "click" );
column.For( li => li.LineItem.InvoiceUnitNetPrice ).Named( "Unit net price " ).Attributes( name => ".LineItem.InvoiceUnitNetPrice", #class => "click" );
column.For( li => li.LineItem.InvoiceQuantity ).Attributes( name => ".LineItem.InvoiceQuantity", #class => "click" );
})
.Render();
//rest of the code
Html.Submit("_submit", "Save");
Right now You can edit in place values, but it doesn't upgrade corresponding model.
All the magic happens after user clicks submit button:
$(document).ready(function() {
$('#_submit').click(function(e) {
e.preventDefault();
$('#InvoiceGrid tbody tr').each(function(index) {
var hidden = $('<input />').attr({ type: 'hidden', name: 'InvoiceLines.Index', value: index });
$(this).children('td:first-child').before(hidden);
$(this).children('td:not(:first-child)').each(function() {
$(this).append($('<input />').attr({ type: 'hidden', value: $(this).text(), name: 'InvoiceLines[' + index + ']' + $(this).attr('name') }));
});
});
$('form').submit();
});
//editable stuff
$('.click').editable(function(value, settings) {
return (value);
}, { submit: 'OK' });
});
In every TD I create hidden input, with value from that TD, in every row input with Index, and the most important here is 'name' attribute: Name of collection in Model[here goes index].rest.of.path, so in this particular case (example):
InvoiceLines[2].LineItem.ItemDescription
Hope it'll help, because rich grid isn't always an answer ;)
Regards
Mateusz
I would checkout one of the javascript UI libraries first:
ExtJS Grid
Yahoo DataTable
Flexigrid
WebForms are easier when it comes to quickly developing rich UI's like editable grids.
Last night I implemented a simple solution: form + table inside, using input fields in the cells with naming convention as described in Phil Haack's blog (thanks to #BengtBe for link).
It's working but its a bit fiddly (e.g. adding rows with jquery requires me to work out the next unused index).
So I am still looking for more solutions.
One I have discovered is the extjs library which provides a very rich grid. I have yet to work out whether there is an easy way to post back the grid data to one of my controller actions yet though...