Search Results

Search found 713 results on 29 pages for 'quantity'.

Page 2/29 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Issue pushing object into an array JS

    - by Javacadabra
    I'm having an issue placing an object into my array in javascript. This is the code: $('.confirmBtn').click(function(){ //Get reference to the Value in the Text area var comment = $("#comments").val(); //Create Object var orderComment = { 'comment' : comment }; //Add Object to the Array productArray.push(orderComment); //update cookie $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' }); }); However when I print the array this is the output: Array ( [0] => Array ( [stockCode] => CBL202659/A [quantity] => 8 ) [1] => Array ( [stockCode] => CBL201764 [quantity] => 6 ) [2] => TEST TEST ) I would like it to look like this: Array ( [0] => Array ( [stockCode] => CBL202659/A [quantity] => 8 ) [1] => Array ( [stockCode] => CBL201764 [quantity] => 6 ) [2] Array( [comment] => TEST TEST ) I added products to the array in a similar way and it worked fine: var productArray = []; // Will hold order Items $(".orderBtn").click(function(event){ //Check to ensure quantity > 0 if(quantity == 0){ console.log("Quantity must be greater than 0") }else{//It is so continue //Show the order Box $(".order-alert").show(); event.preventDefault(); //Get reference to the product clicked var stockCode = $(this).closest('li').find('.stock_code').html(); //Get reference to the quantity selected var quantity = $(this).closest('li').find('.order_amount').val(); //Order Item (contains stockCode and Quantity) - Can add whatever data I like here var orderItem = { 'stockCode' : stockCode, 'quantity' : quantity }; //Check if cookie exists if($.cookie('order_cookie') === undefined){ console.log("Creating new cookie"); //Add object to the Array productArray.push(orderItem);

    Read the article

  • How to move to next textfield using keyboardtype numberandpunctuation using textfield notification

    - by Rani
    Hi guys, I am having code ItemsController.h UITextField* quantity; UITextField* rate; UITextField* tax2; ItemController.m quantity=[[UITextField alloc]initWithFrame:CGRectMake(158,10.5,140,30)]; quantity.textColor = [UIColor blackColor]; quantity.font = [UIFont systemFontOfSize:15.0]; quantity.backgroundColor = [UIColor clearColor]; quantity.returnKeyType=UIReturnKeyNext; quantity.keyboardType = UIKeyboardTypeNumbersAndPunctuation; quantity.leftViewMode = UITextFieldViewModeAlways; quantity.delegate = self; rate=[[UITextField alloc]initWithFrame:CGRectMake(158,10.5,140,30)]; rate.textColor = [UIColor blackColor]; rate.font = [UIFont systemFontOfSize:15.0]; rate.backgroundColor = [UIColor clearColor]; rate.returnKeyType=UIReturnKeyNext; rate.keyboardType = UIKeyboardTypeNumbersAndPunctuation; rate.leftViewMode = UITextFieldViewModeAlways; rate.delegate = self; tax2=[[UITextField alloc]initWithFrame:CGRectMake(158,10.5,140,30)]; tax2.textColor = [UIColor blackColor]; tax2.font = [UIFont systemFontOfSize:15.0]; tax2.backgroundColor = [UIColor clearColor]; tax2.returnKeyType=UIReturnKeyDone; tax2.keyboardType = UIKeyboardTypeAlphabet; tax2.leftViewMode = UITextFieldViewModeAlways; tax2.delegate = self; - (BOOL)textFieldShouldReturn:(UITextField*)textField { if(textField==quantity) { [rate becomeFirstResponder]; } if(textField == rate) { [tax2 becomeFirstResponder]; } else if(textField==tax2) { [textField resignFirstResponder]; } return YES; } Using UITextfield notifications while I am moving from quantity textfield to rate textfield the keyboard type is alphabetical its getting actually I gav eit has Number and punctuation why I am not getting. can any one help me to solve this as soon as possible. Thanks in advance.

    Read the article

  • Combine XML elements with xsl

    - by mpenrow
    I have the following xml: <RowSet> <Row> <Number>12345</Number> <Quantity>42</Quantity> </Row> <Row> <Number>12345</Number> <Quantity>12</Quantity> </Row> <Row> <Number>54321</Number> <Quantity>37</Quantity> </Row> </RowSet> I want to use an xsl to combine the elements with the same Number and the resulting should sum the Quantity elements. So the output should look like this: <RowSet> <Row> <Number>12345</Number> <Quantity>64</Quantity> </Row> <Row> <Number>54321</Number> <Quantity>37</Quantity> </Row> </RowSet>

    Read the article

  • Android AlertDialog wait for result in calling activity

    - by insanesam
    I am trying to use an AlertDialog in my app to select the quantity of an item. The problem is that the activity that calls the AlertDialog doesn't wait for it to update the item before it adds it to the SQLite Database and change intents. At the moment, the QuantitySelector (AlertDialog) appears, then disappears straight away and changes the MealActivity class (which is just a ListView that reads from the database) through the intent change with an update to the database with quantity 0. I need the Activity to wait for the AlertDialog to close before it updates the database. What would be the correct way of implementing this? Here is some code for you: QuantitySelector (which runs the alertdialog): public class QuantitySelector{ protected static final int RESULT_OK = 0; private Context _context; private DatabaseHandler db; private HashMap<String, Double> measures; private Item item; private View v; private EditText quan; private NumberPicker pick; private int value; private Quantity quantity; /** * Function calls the quantity selector AlertDialog * @param _c: The application context * @param item: The item to be added to consumption * @return The quantity that is consumed */ public void select(Context _c, Item item, Quantity quantity){ this._context = _c; this.item = item; this.quantity = quantity; db = new DatabaseHandler(_context); //Get the measures to display createData(); //Set up the custom view LayoutInflater inflater = LayoutInflater.from(_context); v = inflater.inflate(R.layout.quantity_selector, null); //Set up the input fields quan = (EditText) v.findViewById(R.id.quantityNumber); pick = (NumberPicker) v.findViewById(R.id.numberPicker1); //Set up the custom measures into pick pick.setMaxValue(measures.size()-1); pick.setDisplayedValues(measures.keySet().toArray(new String[0])); //Start the alert dialog runDialog(); } public void createData(){ measures = new HashMap<String, Double>(); //Get the measurements from the database if(item!=null){ measures.putAll(db.getMeasures(item)); } //Add grams as the default measurement if(!measures.keySet().contains("grams")){ //Add grams as a standard measure measures.put("grams", 1.0); } } public void runDialog(){ AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity") .setView(v) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //Change the consumption to the new quantity if(!quan.getText().toString().matches("")){ value = Integer.parseInt(quan.getText().toString()); //Check if conversion from other units is needed String s[] = pick.getDisplayedValues(); String a = s[pick.getValue()]; //Convert the chosen measure back to grams if(!a.equals("grams")){ for(String m : measures.keySet()){ if(m==a){ value = (int) (value * measures.get(m)); } } } } quantity.setQuantity(value); dialog.dismiss(); } }) .setNegativeButton("Cancel", null).create(); dialog.show(); } } The method from favouritesAdapter (which calls the alertdialog): add.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { QuantitySelector q = new QuantitySelector(); Quantity quan = new Quantity(); q.select(_context, db.getItem(p.getID()), quan); db.addConsumption(p.getID(), p.getFavouriteShortName(), quan.getQuantity(), "FAVOURITE"); Intent intent = new Intent(_context,MealActivity.class); _context.startActivity(intent); } }); All help is appreciated :)

    Read the article

  • Possible SWITCH Optimization in DAX – #powerpivot #dax #tabular

    - by Marco Russo (SQLBI)
    In one of the Advanced DAX Workshop I taught this year, I had an interesting discussion about how to optimize a SWITCH statement (which could be frequently used checking a slicer, like in the Parameter Table pattern). Let’s start with the problem. What happen when you have such a statement? Sales :=     SWITCH (         VALUES ( Period[Period] ),         "Current", [Internet Total Sales],         "MTD", [MTD Sales],         "QTD", [QTD Sales],         "YTD", [YTD Sales],          BLANK ()     ) The SWITCH statement is in reality just syntax sugar for a nested IF statement. When you place such a measure in a pivot table, for every cell of the pivot table the IF options are evaluated. In order to optimize performance, the DAX engine usually does not compute cell-by-cell, but tries to compute the values in bulk-mode. However, if a measure contains an IF statement, every cell might have a different execution path, so the current implementation might evaluate all the possible IF branches in bulk-mode, so that for every cell the result from one of the branches will be already available in a pre-calculated dataset. The price for that could be high. If you consider the previous Sales measure, the YTD Sales measure could be evaluated for all the cells where it’s not required, and also when YTD is not selected at all in a Pivot Table. The actual optimization made by the DAX engine could be different in every build, and I expect newer builds of Tabular and Power Pivot to be better than older ones. However, we still don’t live in an ideal world, so it could be better trying to help the engine finding a better execution plan. One student (Niek de Wit) proposed this approach: Selection := IF (     HASONEVALUE ( Period[Period] ),     VALUES ( Period[Period] ) ) Sales := CALCULATE (     [Internet Total Sales],     FILTER (         VALUES ( 'Internet Sales'[Order Quantity] ),         'Internet Sales'[Order Quantity]             = IF (                 [Selection] = "Current",                 'Internet Sales'[Order Quantity],                 -1             )     ) )     + CALCULATE (         [MTD Sales],         FILTER (             VALUES ( 'Internet Sales'[Order Quantity] ),             'Internet Sales'[Order Quantity]                 = IF (                     [Selection] = "MTD",                     'Internet Sales'[Order Quantity],                     -1                 )         )     )     + CALCULATE (         [QTD Sales],         FILTER (             VALUES ( 'Internet Sales'[Order Quantity] ),             'Internet Sales'[Order Quantity]                 = IF (                     [Selection] = "QTD",                     'Internet Sales'[Order Quantity],                     -1                 )         )     )     + CALCULATE (         [YTD Sales],         FILTER (             VALUES ( 'Internet Sales'[Order Quantity] ),             'Internet Sales'[Order Quantity]                 = IF (                     [Selection] = "YTD",                     'Internet Sales'[Order Quantity],                     -1                 )         )     ) At first sight, you might think it’s impossible that this approach could be faster. However, if you examine with the profiler what happens, there is a different story. Every original IF’s execution branch is now a separate CALCULATE statement, which applies a filter that does not execute the required measure calculation if the result of the FILTER is empty. I used the ‘Internet Sales’[Order Quantity] column in this example just because in Adventure Works it has only one value (every row has 1): in the real world, you should use a column that has a very low number of distinct values, or use a column that has always the same value for every row (so it will be compressed very well!). Because the value –1 is never used in this column, the IF comparison in the filter discharge all the values iterated in the filter if the selection does not match with the desired value. I hope to have time in the future to write a longer article about this optimization technique, but in the meantime I’ve seen this optimization has been useful in many other implementations. Please write your feedback if you find scenarios (in both Power Pivot and Tabular) where you obtain performance improvements using this technique!

    Read the article

  • How do I lookup a 'quantity' of items in excel?

    - by KronoS
    Let's say I have a quatity of items: 1 2 3 4 5 4 3 2 1 2 3 4 in a column of cells. What I want to be able to do is count the quantity how many unique "items" there are in this array: 1 -- 2 2 -- 3 3 -- 3 4 .. 3 And so forth. I want the table to look like this: Also, is there a way to accomplish this if I don't know all of the values of the array to begin with? I'm looking for a way to have excel search an array, find a unique value, count how many times that value is in the array, and then move onto the next values.

    Read the article

  • how to make Excel/Access data have more than one quantity in a table?

    - by Xrave
    Sorry for the confusing question, I'm not sure how to word it right: here's a mock sample of my data Name: Cheeseburger Date: 1/20/2011 Stock: 30 Price: 200 Name: Hamburger Date: 1/20/2011 Stock: 12 Price: 180 Name: Cheeseburger Date: 1/21/2011 Stock: 31 Price: 210 ... I will have to make a table in excel or access capable of looking up the stock and price trends of a particular brand through time. Trouble is, I have two independent variables (Stock, Price) and two known dependent variables (Name, Date). So, I cannot use a simple table where the x axis is the name, y axis is the time, and the cells represent a quantity - each cell have to represent two quantities (Stock, Price) Does anyone know how to do that? Thanks.

    Read the article

  • How do I create a loop based off this array?

    - by dmanexe
    I'm trying to process this array, first testing for the presence of a check, then extrapolating the data from quantity to return a valid price. Here's the input for fixed amounts of items, with no variable quantity. <input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>"> <input type="hidden" name="measure[<?=$item->id?>][quantity]" value="1" /> Here's the inputs for variable amounts of items. <input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>"> <input class="item_mult" value="0" type="text" name="measure[<?=$item->id?>][quantity]" /> So, the resulting array is multidimensional. Here's an output: Array ( [1] => Array ( [quantity] => 1 ) [2] => Array ( [quantity] => 1 ) [3] => Array ( [quantity] => 1 ) ... [14] => Array ( [checked] => 14 [quantity] => 999 ) ) Here's the loop I'm using to take this array and process items checked off the form in the first place. I guess the question essentially boils down to how do I structure my conditional statement to incorporate the multi-dimensional array? foreach($field as $value): if ($value['checked'] == TRUE) { $query = $this->db->get_where('items', array('id' => $value['checked']))->row(); #Test to see if quantity input is present if ($value['quantity'] == TRUE) { $newprice = $value['quantity'] * $query->price; $totals[] = $newprice; } #Just return the base value if not else { $newprice = $query->price; $totals[] = $newprice; } } else { } ?> <p><?=$query->name?> - <?=money_format('%(#10n', $newprice)?></p> <? endforeach; ?>

    Read the article

  • KnockoutJS showing a sorted list by item category

    - by Darksbane
    I just started learning knockout this week and everything has gone well except for this one issue. I have a list of items that I sort multiple ways but one of the ways I want to sort needs to have a different display than the standard list. As an example lets say I have this code var BetterListModel = function () { var self = this; food = [ { "name":"Apple", "quantity":"3", "category":"Fruit", "cost":"$1", },{ "name":"Ice Cream", "quantity":"1", "category":"Dairy", "cost":"$6", },{ "name":"Pear", "quantity":"2", "category":"Fruit", "cost":"$2", },{ "name":"Beef", "quantity":"1", "category":"Meat", "cost":"$3", },{ "name":"Milk", "quantity":"5", "category":"Dairy", "cost":"$4", }]; self.allItems = ko.observableArray(food); // Initial items // Initial sort self.sortMe = ko.observable("name"); ko.utils.compareItems = function (l, r) { if (self.sortMe() =="cost"){ return l.cost > r.cost ? 1 : -1 } else if (self.sortMe() =="category"){ return l.category > r.category ? 1 : -1 } else if (self.sortMe() =="quantity"){ return l.quantity > r.quantity ? 1 : -1 }else { return l.name > r.name ? 1 : -1 } }; }; ko.applyBindings(new BetterListModel()); and the HTML <p>Your values:</p> <ul class="deckContents" data-bind="foreach:allItems().sort(ko.utils.compareItems)"> <li><div style="width:100%"><div class="left" style="width:30px" data-bind="text:quantity"></div><div class="left fixedWidth" data-bind="text:name"></div> <div class="left fixedWidth" data-bind="text:cost"></div> <div class="left fixedWidth" data-bind="text:category"></div><div style="clear:both"></div></div></li> </ul> <select data-bind="value:sortMe"> <option selected="selected" value="name">Name</option> <option value="cost">Cost</option> <option value="category">Category</option> <option value="quantity">Quantity</option> </select> </div> So I can sort these just fine by any field I might sort them by name and it will display something like this 3 Apple $1 Fruit 1 Beef $3 Meat 1 Ice Cream $6 Dairy 5 Milk $4 Dairy 2 Pear $2 Fruit Here is a fiddle of what I have so far http://jsfiddle.net/Darksbane/X7KvB/ This display is fine for all the sorts except the category sort. What I want is when I sort them by category to display it like this Fruit 3 Apple $1 Fruit 2 Pear $2 Fruit Meat 1 Beef $3 Meat Dairy 1 Ice Cream $6 Dairy 5 Milk $4 Dairy Does anyone have any idea how I might be able to display this so differently for that one sort?

    Read the article

  • JS Split ( ) to check if substring exists in Array

    - by Javacadabra
    I have an array of products that are stored as Strings in this format productname:quantity. The issue I am running into is that if a user adds one product with a quantity of x it is inserted into the array as it should. However, if they then decide to add more of a particular product a new entry is made into the array instead of checking if the product already exists and adjusting the quantity to the new value. oldQty + newQty. For example this is my array: ["CBL202659/A:1","OUTER9:1","PALLET CARDS:1"] If I add another PALLET CARDS product it creates a new entry rather than updating the quantity of the existing item to 2. New array ["CBL202659/A:1","OUTER9:1","PALLET CARDS:1","PALLET CARDS:1"] I would like the array to end up like this: - updating the quantity ["CBL202659/A:1","OUTER9:1","PALLET CARDS:2"] Currently this is my code: I use the split() method to seperate the String where a colon occurs and store the product name and quantity in two seperate variables. $(".orderBtn").click(function(event){ //Show the order Box $(".order-alert").show(); event.preventDefault(); //Create the Array var productArray = []; //Get reference to the product clicked var stockCode = $(this).closest('li').find('.stock_code').html(); //Get reference to the quantity selected var quantity = $(this).closest('li').find('.order_amount').val(); var item = stockCode + ":" + quantity; var itemCheck = stockCode + ":"; if(quantity == 0){ console.log("Quantity must be greater than 0") }else{ //If no Cookie exists, create one and add the Array if ($.cookie('order_cookie') === undefined) { console.log("CREATE NEW COOKIE"); //Add items to Array productArray.push(item); //Add Array to Cookie $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' }); //If the Cookie already exists do this } else { productArray = JSON.parse($.cookie('order_cookie'));//get ref to array if(productArray.indexOf(itemCheck)!= -1){//It exists so update qty console.log("EXISTS... updating item: " + itemCheck); //var index = productArray.indexOf(item); //var update = productArray[index].split(":"); //var name = update[0]; //var oldQty = update[1]; //console.log(name + ":" + oldQty); //productArray[index] = item; }else{//It does not exist, so add to array console.log("Does not exist... adding new item: " + item); //Append items onto the Array productArray.push(item); } //Update the Cookie $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' }); console.log($.cookie('order_cookie')); } //Display the number of items in the Array in the Order Box $('#order_counter').html(productArray.length); } }); I suppose the real question I am asking here, is if it is possible to search the array for a subString - containing productname: ??

    Read the article

  • C# Changing Objects within a List

    - by kwong22
    Hi, I'm having a little problem changing members of an object in a list using a found index. So this is the method I am currently working with: static void addToInventory(ref List<baseItem> myArray, baseItem item, float maxAmount, ref float currentAmount) { if (currentAmount + item.getWeight() <= maxAmount) { Console.WriteLine("item.Quantity = {0}", item.Quantity); if (myArray.Contains(item)) { Console.WriteLine("Item ({0}) already exists", item.Name); int id = myArray.IndexOf(item); myArray[id].Quantity += item.Quantity;//Change occurs in this line, item.Quantity becomes the same as myArray[id].Quantity } else { Console.WriteLine("Adding new item ({0})", item.Name); myArray.Add(item); } currentAmount += item.getWeight(); } else { Console.WriteLine("Inventory full"); } myArray.Sort(); } This method takes several parameters including the inventory/list. I check if the item fits in and if it does, I see if there is another item of the same name in the list, find the index, and add more of the item. However, the quantity of the item added suddenly becomes the same as the quantity of the item in the list. For some reason, this also changes the quantity of the item outside of the list. So therefore, instead of quantities adding up like this: 1, 2, 3, 4, they add up like this: 1, 2, 4, 8. I've just started to learn how to use lists so if there is anything I'm missing, don't hesitate to criticize. Thanks in advance.

    Read the article

  • class method or named_scope?

    - by Hadi
    i would like to have your opinion in a project i am currently working on. class Product has_many :orders end class Order attr_accessor :deliverable # to contain temporary data on how many items can be delivered for this order belongs_to :product end somehow i want to have Order.all_deliverable that will calculate the Product's quantity, subtract from list of Orders until the Product is empty or there is no more Order for this Product to illustrate Product A, quantity: 20 Product B, quantity: 0 Order 1, require Product A, quantity: 12 Order 2, require Product B, quantity: 10 Order 3, require Product A, quantity: 100 so if i call Order.all_deliverable, it will give Order 1, deliverable:12 Order 3, deliverable: 8 #(20-12) i have been thinking on using named_scope, but i think the logic will be too complex to be put in a named_scope. Any suggestion? the pseudo code for all_deliverable will be something like this: go to each orders find the remaining quantity for specific product deduct the product to max amount of order, if product is not enough, add the maximum product add to the order end From what i read around in the web, named_scope deal mostly like find and have not many method calling and looping.

    Read the article

  • How to increase the value of a quantity field with jQuery?

    - by amir
    I have a form with some quantity field and a plus and minus sign on each side, <form id="myform"> product1 <input type="submit" value="+" id="add"> <input type="text" id="qty1"> <input type="submit value="-" id="minus"> product2 <input type="submit" value="+" id="add"> <input type="text" id="qty2"> <input type="submit value="-" id="minus"> </form> I'd like to increase the value of the field by one if the add button is pressed and decrease by one if minus is pressed. Also the value shouldn't get less than 0. Is there a way to do this in jQuery?

    Read the article

  • Where we should put validation for domain model

    - by adisembiring
    I still looking best practice for domain model validation. Is that good to put the validation in constructor of domain model ? my domain model validation example as follows: public class Order { private readonly List<OrderLine> _lineItems; public virtual Customer Customer { get; private set; } public virtual DateTime OrderDate { get; private set; } public virtual decimal OrderTotal { get; private set; } public Order (Customer customer) { if (customer == null) throw new ArgumentException("Customer name must be defined"); Customer = customer; OrderDate = DateTime.Now; _lineItems = new List<LineItem>(); } public void AddOderLine //.... public IEnumerable<OrderLine> AddOderLine { get {return _lineItems;} } } public class OrderLine { public virtual Order Order { get; set; } public virtual Product Product { get; set; } public virtual int Quantity { get; set; } public virtual decimal UnitPrice { get; set; } public OrderLine(Order order, int quantity, Product product) { if (order == null) throw new ArgumentException("Order name must be defined"); if (quantity <= 0) throw new ArgumentException("Quantity must be greater than zero"); if (product == null) throw new ArgumentException("Product name must be defined"); Order = order; Quantity = quantity; Product = product; } } Thanks for all of your suggestion.

    Read the article

  • How do I make these fields autopopulate from the database?

    - by dmanexe
    I have an array, which holds values like this: $items_pool = Array ( [0] => Array ( [id] => 1 [quantity] => 1 ) [1] => Array ( [id] => 2 [quantity] => 1 ) [2] => Array ( [id] => 72 [quantity] => 6 ) [3] => Array ( [id] => 4 [quantity] => 1 ) [4] => Array ( [id] => 5 [quantity] => 1 ) [5] => Array ( [id] => 7 [quantity] => 1 ) [6] => Array ( [id] => 8 [quantity] => 1 ) [7] => Array ( [id] => 9 [quantity] => 1 ) [8] => Array ( [id] => 19 [quantity] => 1 ) [9] => Array ( [id] => 20 [quantity] => 1 ) [10] => Array ( [id] => 22 [quantity] => 1 ) [11] => Array ( [id] => 29 [quantity] => 0 ) ) Next, I have a form that I am trying to populate. It loops through the item database, prints out all the possible items, and checks the ones that are already present in $items_pool. <?php foreach ($items['items_poolpackage']->result() as $item): ?> <input type="checkbox" name="measure[<?=$item->id?>][checkmark]" value="<?=$item->id?>"> <?php endforeach; ?> I know what logically I'm trying to accomplish here, but I can't figure out the programming. What I'm looking for, written loosely is something like this (not real code): <input type="checkbox" name="measure[<?=$item->id?>][checkmark]" value="<?=$item->id?>" <?php if ($items_pool['$item->id']) { echo "SELECTED"; } else { }?>> Specifically this conditional loop through the array, through all the key values (the ID) and if there's a match, the checkbox is selected. <?php if ($items_pool['$item->id']) { echo "SELECTED"; } else { }?> I understand from a loop structured like this that it may mean a lot of 'extra' processing. TL;DR - I need to echo within a loop if the item going through the loop exists within another array.

    Read the article

  • Dont Throw Duplicate Exceptions

    In your code, youll sometimes have write code that validates input using a variety of checks.  Assuming you havent embraced AOP and done everything with attributes, its likely that your defensive coding is going to look something like this: public void Foo(SomeClass someArgument) { if(someArgument == null) { throw new InvalidArgumentException("someArgument"); } if(!someArgument.IsValid()) { throw new InvalidArgumentException("someArgument"); }   // Do Real Work } Do you see a problem here?  Heres the deal Exceptions should be meaningful.  They have value at a number of levels: In the code, throwing an exception lets the develop know that there is an unsupported condition here In calling code, different types of exceptions may be handled differently At runtime, logging of exceptions provides a valuable diagnostic tool Its this last reason I want to focus on.  If you find yourself literally throwing the exact exception in more than one location within a given method, stop.  The stack trace for such an exception is likely going to be identical regardless of which path of execution led to the exception being thrown.  When that happens, you or whomever is debugging the problem will have to guess which exception was thrown.  Guessing is a great way to introduce additional problems and/or greatly increase the amount of time require to properly diagnose and correct any bugs related to this behavior. Dont Guess Be Specific When throwing an exception from multiple code paths within the code, be specific.  Virtually ever exception allows a custom message use it and ensure each case is unique.  If the exception might be handled differently by the caller, than consider implementing a new custom exception type.  Also, dont automatically think that you can improve the code by collapsing the if-then logic into a single call with short-circuiting (e.g. if(x == null || !x.IsValid()) ) that will guarantee that you cant easily throw different information into the message as easily as constructing the exception separately in each case. The code above might be refactored like so:   public void Foo(SomeClass someArgument) { if(someArgument == null) { throw new ArgumentNullException("someArgument"); } if(!someArgument.IsValid()) { throw new InvalidArgumentException("someArgument"); }   // Do Real Work } In this case its taking advantage of the fact that there is already an ArgumentNullException in the framework, but if you didnt have an IsValid() method and were doing validation on your own, it might look like this: public void Foo(SomeClass someArgument) { if(someArgument.Quantity < 0) { throw new InvalidArgumentException("someArgument", "Quantity cannot be less than 0. Quantity: " + someArgument.Quantity); } if(someArgument.Quantity > 100) { throw new InvalidArgumentException("someArgument", "SomeArgument.Quantity cannot exceed 100. Quantity: " + someArgument.Quantity); }   // Do Real Work }   Note that in this last example, Im throwing the same exception type in each case, but with different Message values.  Im also making sure to include the value that resulted in the exception, as this can be extremely useful for debugging.  (How many times have you wished NullReferenceException would tell you the name of the variable it was trying to reference?) Dont add work to those who will follow after you to maintain your application (especially since its likely to be you).  Be specific with your exception messages follow DRY when throwing exceptions within a given method by throwing unique exceptions for each interesting case of invalid state. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Preserving hierarchy when converting .csv file to xml or json

    - by Simon Levinson
    Hello I have a question concerning translating data from a CSV into XML or JSON where it is essential to preserve the heirarchy of the data. For example, if I have CSV data like this: type,brand,country,quantity apple,golden_delicious,english,1 apple,golden_delicious,french,2 apple,cox,,4 apple,braeburn,,1 banana,,carribean,6 banana,,central_america,7 clememtine,,,3 What I want is to preserve hierarchy in the XML so that I get something like: <fruit> <type = "apple"> <brand = "golden_delicious"> <country = "english" quantity = "1"> <country = "french" quantity = "2"> </brand> <brand = "cox"> <quantity = "4"> </brand> <brand = "braeburn"> <quantity = "1"> </brand> </type> <type = "banana"> <country = "carribean" quantity = "6"> <country = "central_america" quantity = "7"> </type> <type = "clementine"> <quantity = "3"> </type> <fruit /> Is it best to try to use JAXP or to convert the above into a table simply of parent, child and then writing the data to an array of strings for processing,? Like this: parent,child fruit,apple apple,golden_delicious golden_delicious,english golden_delicious,french english,1 french,2 apple,cox cox,4 apple,braeburn braeburn,1 And so on. Or is there a better way? Thanks Simon Levinson

    Read the article

  • Change array format in PHP.

    - by Muhammad Sajid
    I have an array like: Array ( [6] => Array ( [quantity] => 23 [orgId] => 6 [validity] => 20 ) [2] => Array ( [quantity] => 5 [orgId] => 2 [validity] => 2 ) [5] => Array ( [quantity] => 5 [orgId] => 5 [validity] => 4 ) [4] => Array ( [quantity] => 7 [orgId] => 4 [validity] => 10 ) ) and i want to show that like this: Array ( [0] => Array ( [quantity] => 23 [orgId] => 6 [validity] => 20 ) [1] => Array ( [quantity] => 5 [orgId] => 2 [validity] => 2 ) [2] => Array ( [quantity] => 5 [orgId] => 5 [validity] => 4 ) [3] => Array ( [quantity] => 7 [orgId] => 4 [validity] => 10 ) ) To do that i used array_push & some other technique but fail. can someone help me thanks.

    Read the article

  • Compute weighted averages for large numbers

    - by Travis
    I'm trying to get the weighted average of a few numbers. Basically I have: Price - 134.42 Quantity - 15236545 There can be as few as one or two or as many as fifty or sixty pairs of prices and quantities. I need to figure out the weighted average of the price. Basically, the weighted average should give very little weight to pairs like Price - 100000000.00 Quantity - 3 and more to the pair above. The formula I currently have is: ((price)(quantity) + (price)(quantity) + ...)/totalQuantity So far I have this done: double optimalPrice = 0; int totalQuantity = 0; double rolling = 0; System.out.println(rolling); Iterator it = orders.entrySet().iterator(); while(it.hasNext()) { System.out.println("inside"); Map.Entry order = (Map.Entry)it.next(); double price = (Double)order.getKey(); int quantity = (Integer)order.getValue(); System.out.println(price + " " + quantity); rolling += price * quantity; totalQuantity += quantity; System.out.println(rolling); } System.out.println(rolling); return totalQuantity / rolling; The problem is I very quickly max out the "rolling" variable. How can I actually get my weighted average? Thanks!

    Read the article

  • Flex bar chart with Two Y axis

    - by user345522
    I am trying to create a bar char in action 3 script. But for some reason I am getting 2 y-axis and no x axis. Can some one help spot the error. I have said "placement " bottom. The standalone code snippet is below. enter code here [Bindable] public var QUANTITY:ArrayCollection = new ArrayCollection([ {date:"22-Aug-05", quantity:1575.9}, {date:"23-Aug-05", quantity:1603.}, {date:"24-Aug-05", quantity:1507.1}, {date:"25-Aug-05", quantity:1568.8}, ]); private function getBarChartData(evt:MouseEvent):void{ var title:String = "ASDFZXCVB"; var pnlChart:Panel = new Panel(); pnlChart.title = title; pnlChart.height = 750; { var categoryAxisDate:CategoryAxis = new CategoryAxis(); categoryAxisDate.categoryField = "date"; var linearVolumeAxis:LinearAxis = new LinearAxis(); linearVolumeAxis.minimum = 1500; linearVolumeAxis.maximum = 1700; var colChart:ColumnChart = new ColumnChart(); colChart.showDataTips = true; { var horizontalAxisDateRenderer:AxisRenderer = new AxisRenderer(); horizontalAxisDateRenderer.axis = categoryAxisDate; horizontalAxisDateRenderer.placement = "bottom"; var quantityRenderer:AxisRenderer = new AxisRenderer(); quantityRenderer.axis = linearVolumeAxis; quantityRenderer.placement = "left"; colChart.horizontalAxisRenderers.push(horizontalAxisDateRenderer); colChart.verticalAxisRenderers.push(quantityRenderer); { var quantityColumnSeries:ColumnSeries = new ColumnSeries(); quantityColumnSeries.horizontalAxis = categoryAxisDate; quantityColumnSeries.yField="quantity"; quantityColumnSeries.displayName ="QUANTITY"; quantityColumnSeries.dataProvider = QUANTITY; quantityColumnSeries.verticalAxis = linearVolumeAxis; colChart.series.push(quantityColumnSeries); } } pnlChart.addChild(colChart); } canvasReportId.addChild(pnlChart); } ]] <mx:Button label="Submit" click="getBarChartData(event)" x="293" y="4"/> </mx:Canvas>

    Read the article

  • Translate query to NHibernate

    - by Rob Walker
    I am trying to learn NHibernate, and am having difficulty translating a SQL query into one using the criteria API. The data model has tables: Part (Id, Name, ...), Order (Id, PartId, Qty), Shipment (Id, PartId, Qty) For all the parts I want to find the total quantity ordered and the total quantity shipped. In SQL I have: select shipment.part_id, sum(shipment.quantity), sum(order.quantity) from shipment cross join order on order.part_id = shipment.part_id group by shipment.part_id Alternatively: select id, (select sum(quantity) from shipment where part_id = part.id), (select sum(quantity) from order where part_id = part.id) from part But the latter query takes over twice as long to execute. Any suggestions on how to create these queries in (fluent) NHibernate? I have all the tables mapped and loading/saving/etc the entities works fine.

    Read the article

  • Creating items in groups in Rails

    - by LearnRails
    My product table is id type price location 1 chips $3 aisle3 I have a question with adding the products in groups. There is a quantity field(nonmodel) where the user can enter the quantity While adding a new product if the user enters: type: soda quantity: 3 Then there 3 records should be created in product model with type= soda like the following. id type 2 soda 3 soda 4 soda If user enters location: aisle4 quantity: 2 Then id location 5 ailse4 6 ailse4 Can you tell me how to pass the nonmodel field 'quantity' to the rails(model or controller) and how use it to add the products in groups as mentioned above? or should I create a column called quantity in my product table? Will the history be updated too for all these new records with after_create filter which I already have ? Is there any good tutorial or book which shows how to pass such nonmodel html/javascript fields from view to rails and then back to the view? Any help will be greatly appreciated. Thanks

    Read the article

  • Rails 3 ActiveModel Nested Class I18n

    - by Dave
    Given the following class definition in ruby: class Conversation class Message include ActiveModel::Validations attr_accessor :quantity validates :quantity, :presence => true end end How can you use i18n to customize to error message. For example the correct lookup for the class Conversation would be activemodel: errors: models: conversation: attributes: quantity: blank: "Some custom message" But what is it for the Message class? I tried: activemodel: errors: models: conversation: message: attributes: quantity: blank: "Some custom message" activemodel: errors: models: message: attributes: quantity: blank: "Some custom message" activemodel: errors: models: conversation::message: attributes: quantity: blank: "Some custom message" None of them work Any ideas or is this a bug with ActiveModel or I18n?

    Read the article

  • ASP.NET MVC 2 Model Binding for a Collection

    - by nmarun
    Yes, my yet another post on Model Binding (previous one is here), but this one uses features presented in MVC 2. How I got to writing this blog? Well, I’m on a project where we’re doing some MVC things for a shopping cart. Let me show you what I was working with. Below are my model classes: 1: public class Product 2: { 3: public int Id { get; set; } 4: public string Name { get; set; } 5: public int Quantity { get; set; } 6: public decimal UnitPrice { get; set; } 7: } 8:   9: public class Totals 10: { 11: public decimal SubTotal { get; set; } 12: public decimal Tax { get; set; } 13: public decimal Total { get; set; } 14: } 15:   16: public class Basket 17: { 18: public List<Product> Products { get; set; } 19: public Totals Totals { get; set;} 20: } The view looks as below:  1: <h2>Shopping Cart</h2> 2:   3: <% using(Html.BeginForm()) { %> 4: 5: <h3>Products</h3> 6: <% for (int i = 0; i < Model.Products.Count; i++) 7: { %> 8: <div style="width: 100px;float:left;">Id</div> 9: <div style="width: 100px;float:left;"> 10: <%= Html.TextBox("ID", Model.Products[i].Id) %> 11: </div> 12: <div style="clear:both;"></div> 13: <div style="width: 100px;float:left;">Name</div> 14: <div style="width: 100px;float:left;"> 15: <%= Html.TextBox("Name", Model.Products[i].Name) %> 16: </div> 17: <div style="clear:both;"></div> 18: <div style="width: 100px;float:left;">Quantity</div> 19: <div style="width: 100px;float:left;"> 20: <%= Html.TextBox("Quantity", Model.Products[i].Quantity)%> 21: </div> 22: <div style="clear:both;"></div> 23: <div style="width: 100px;float:left;">Unit Price</div> 24: <div style="width: 100px;float:left;"> 25: <%= Html.TextBox("UnitPrice", Model.Products[i].UnitPrice)%> 26: </div> 27: <div style="clear:both;"><hr /></div> 28: <% } %> 29: 30: <h3>Totals</h3> 31: <div style="width: 100px;float:left;">Sub Total</div> 32: <div style="width: 100px;float:left;"> 33: <%= Html.TextBox("SubTotal", Model.Totals.SubTotal)%> 34: </div> 35: <div style="clear:both;"></div> 36: <div style="width: 100px;float:left;">Tax</div> 37: <div style="width: 100px;float:left;"> 38: <%= Html.TextBox("Tax", Model.Totals.Tax)%> 39: </div> 40: <div style="clear:both;"></div> 41: <div style="width: 100px;float:left;">Total</div> 42: <div style="width: 100px;float:left;"> 43: <%= Html.TextBox("Total", Model.Totals.Total)%> 44: </div> 45: <div style="clear:both;"></div> 46: <p /> 47: <input type="submit" name="Submit" value="Submit" /> 48: <% } %> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Nothing fancy, just a bunch of div’s containing textboxes and a submit button. Just make note that the textboxes have the same name as the property they are going to display. Yea, yea, I know. I’m displaying unit price as a textbox instead of a label, but that’s beside the point (and trust me, this will not be how it’ll look on the production site!!). The way my controller works is that initially two dummy products are added to the basked object and the Totals are calculated based on what products were added in what quantities and their respective unit price. So when the page loads in edit mode, where the user can change the quantity and hit the submit button. In the ‘post’ version of the action method, the Totals get recalculated and the new total will be displayed on the screen. Here’s the code: 1: public ActionResult Index() 2: { 3: Product product1 = new Product 4: { 5: Id = 1, 6: Name = "Product 1", 7: Quantity = 2, 8: UnitPrice = 200m 9: }; 10:   11: Product product2 = new Product 12: { 13: Id = 2, 14: Name = "Product 2", 15: Quantity = 1, 16: UnitPrice = 150m 17: }; 18:   19: List<Product> products = new List<Product> { product1, product2 }; 20:   21: Basket basket = new Basket 22: { 23: Products = products, 24: Totals = ComputeTotals(products) 25: }; 26: return View(basket); 27: } 28:   29: [HttpPost] 30: public ActionResult Index(Basket basket) 31: { 32: basket.Totals = ComputeTotals(basket.Products); 33: return View(basket); 34: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } That’s that. Now I run the app, I see two products with the totals section below them. I look at the view source and I see that the input controls have the right ID, the right name and the right value as well. 1: <input id="ID" name="ID" type="text" value="1" /> 2: <input id="Name" name="Name" type="text" value="Product 1" /> 3: ... 4: <input id="ID" name="ID" type="text" value="2" /> 5: <input id="Name" name="Name" type="text" value="Product 2" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } So just as a regular user would do, I change the quantity value of one of the products and hit the submit button. The ‘post’ version of the Index method gets called and I had put a break-point on line 32 in the above snippet. When I hovered my mouse on the ‘basked’ object, happily assuming that the object would be all bound and ready for use, I was surprised to see both basket.Products and basket.Totals were null. Huh? A little research and I found out that the reason the DefaultModelBinder could not do its job is because of a naming mismatch on the input controls. What I mean is that when you have to bind to a custom .net type, you need more than just the property name. You need to pass a qualified name to the name property of the input control. I modified my view and the emitted code looked as below: 1: <input id="Product_Name" name="Product.Name" type="text" value="Product 1" /> 2: ... 3: <input id="Product_Name" name="Product.Name" type="text" value="Product 2" /> 4: ... 5: <input id="Totals_SubTotal" name="Totals.SubTotal" type="text" value="550" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Now, I update the quantity and hit the submit button and I see that the Totals object is populated, but the Products list is still null. Once again I went: ‘Hmm.. time for more research’. I found out that the way to do this is to provide the name as: 1: <%= Html.TextBox(string.Format("Products[{0}].ID", i), Model.Products[i].Id) %> 2: <!-- this will be rendered as --> 3: <input id="Products_0__ID" name="Products[0].ID" type="text" value="1" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } It was only now that I was able to see both the products and the totals being properly bound in the ‘post’ action method. Somehow, I feel this is kinda ‘clunky’ way of doing things. Seems like people at MS felt in a similar way and offered us a much cleaner way to solve this issue. The simple solution is that instead of using a Textbox, we can either use a TextboxFor or an EditorFor helper method. This one directly spits out the name of the input property as ‘Products[0].ID and so on. Cool right? I totally fell for this and changed my UI to contain EditorFor helper method. At this point, I ran the application, changed the quantity field and pressed the submit button. Of course my basket object parameter in my action method was correctly bound after these changes. I let the app complete the rest of the lines in the action method. When the page finally rendered, I did see that the quantity was changed to what I entered before the post. But, wait a minute, the totals section did not reflect the changes and showed the old values. My status: COMPLETELY PUZZLED! Just to recap, this is what my ‘post’ Index method looked like: 1: [HttpPost] 2: public ActionResult Index(Basket basket) 3: { 4: basket.Totals = ComputeTotals(basket.Products); 5: return View(basket); 6: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } A careful debug confirmed that the basked.Products[0].Quantity showed the updated value and the ComputeTotals() method also returns the correct totals. But still when I passed this basket object, it ended up showing the old totals values only. I began playing a bit with the code and my first guess was that the input controls got their values from the ModelState object. For those who don’t know, the ModelState is a temporary storage area that ASP.NET MVC uses to retain incoming attempted values plus binding and validation errors. Also, the fact that input controls populate the values using data taken from: Previously attempted values recorded in the ModelState["name"].Value.AttemptedValue Explicitly provided value (<%= Html.TextBox("name", "Some value") %>) ViewData, by calling ViewData.Eval("name") FYI: ViewData dictionary takes precedence over ViewData's Model properties – read more here. These two indicators led to my guess. It took me quite some time, but finally I hit this post where Brad brilliantly explains why this is the preferred behavior. My guess was right and I, accordingly modified my code to reflect the following way: 1: [HttpPost] 2: public ActionResult Index(Basket basket) 3: { 4: // read the following posts to see why the ModelState 5: // needs to be cleared before passing it the view 6: // http://forums.asp.net/t/1535846.aspx 7: // http://forums.asp.net/p/1527149/3687407.aspx 8: if (ModelState.IsValid) 9: { 10: ModelState.Clear(); 11: } 12:   13: basket.Totals = ComputeTotals(basket.Products); 14: return View(basket); 15: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } What this does is that in the case where your ModelState IS valid, it clears the dictionary. This enables the values to be read from the model directly and not from the ModelState. So the verdict is this: If you need to pass other parameters (like html attributes and the like) to your input control, use 1: <%= Html.TextBox(string.Format("Products[{0}].ID", i), Model.Products[i].Id) %> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Since, in EditorFor, there is no direct and simple way of passing this information to the input control. If you don’t have to pass any such ‘extra’ piece of information to the control, then go the EditorFor way. The code used in the post can be found here.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >