Is this a good approach for avoiding postbacks? - c#

I'm creating an e-commerce site in ASP.NET.
For the actual products available to buy, I've placed a box with two arrows, which allow the user to modify the quantity of a specific item. This feature has been implemented in Javascript, so as to avoid postbacks which would be the result of managing this through ASP.NET/C# code.
Now the problem is, how am I to store the items which are ordered? Since the user can modify the quantities and products selected on the fly, I need to figure out how to pass the selected items onto another aspx page (for checkout).
Due to strict requirements, I cannot use a shopping cart. Just literally allow the user to play around with quantities of items, then once the 'Checkout' button is pressed, the user is directed to a payment page where his items are displayed.
Since the selection of items is carried out in javascript, I need to find a way of passing the selected items to another .aspx page.
I thought of storing the items in a javascript data structure, sort of like a table. A product ID will be stored in one field, and the quantity of te respective product will be stored in another field. Once the checkout button is pressed, this data structure is passed on to the .aspx page and handled from there in C# code.
It seems a bit coplicated, especiially since the javascript structure may be modified multiple times if the user changes the selected products and quantities before pressing 'checkout'.
Any ideas?

You can use JSON data in your javascript code and then pass it to ASP page with GET or POST.
At the server side you can parse JSON to .net object using JavaScriptSerializer or DataContractJsonSerializer.
Updated: In JavaScript JSON data should be looked this way:
var orders = [
{
"ProductID" : 123,
"SomeData": "some additional data if needed",
"OrderedCount": 3
},
{
"ProductID" : 321,
"SomeData": "some new additional data if needed",
"OrderedCount": 1
}
];
It is an array of orders.

Sounds like it should be pretty easy. On the page with the quantity boxes and checkboxes, you just run an iterator over them, finding first products to be ordered (assuming the page is not already displaying only products to be ordered) and then within that set finding out the quantities. You can then serialize these or otherwise create a data object and pass these to your ASP page with GET or POST (whatever you prefer).
In other words, sort of like the idea you already had, but I don't see it as being overly complicated to create or manage. Most of your functions can be reusable and repeatable.
As per Jared Farresh's comment, cookies make good sense, too.

From the comments under your question it appears like your apprehension to a "shopping cart" is related to the overhead that would likely go along with a server-side shopping cart.
But, have you considered using a client-side shopping cart? You can still use the shopping cart metaphor to reduce the complexity of the "javascript data structure, sort of like a table", without having a persistent back-end implementation.
simpleCart js is an open source, light-weight implementation of this concept. It works by storing the data in a cookie. You can retrieve it directly by querying the object or you can specify a class on an HTML element and the start up script will automatically replace the inner HTML of that element with the requested value. For example, a <span class="simpleCart_quantity"></span> will immediately have the quantity of items in the cart as its inner HTML after the page loads.
You might also want to check out this post that I asked when I was working on a project with similar requirements: Open Source client-side Shopping Cart - jQuery/Cookies

Related

Sitecore: Drop Down Search Menu

I am in need of hopefully an example for a drop down list search function. Not sure what the correct terminology would be.
Needed:
Two drop down lists then a submit button. First being of Country, then the second being of Department. So say you picked France and HR, it would display a contact person below.
Is there any examples of something of this sort? Would be nice have code in CS then have my end user be able to add and link the two together in Sitecore. So they could add Countries they would like, departments they would like, then the respected person linked to the two fields.
So if I understand you correctly, you're taking multiple inputs and producing results for that combination of them. I'll make some assumptions and try to give you enough direction to get started. This will take a bit of explaining.
Starting from scratch, we've got a Contact template that has, at least, a Country and Department field. You'll need templates and lists of items for each of those two fields. You could get these values from another source, but let's just keep it simple for now and use lists of items. This sounds hierarchical, so I'd suggest you define your departments as children of your Country items. What other fields are on these items doesn't really matter at the moment.
Next, you'll want to communicate the end-user's selections back to your Sitecore instance. I'll assume that you're using Sitecore MVC, but the same principles apply for web forms.
Set up a controller to parse your parameters, country and department, and a form in your View with <select> elements populated from the lists of countries and departments. When the country selector is changed, you can either reload the page with the value set as a request parameter or use AJAX to ask your controller directly. If you structure the model so that it doesn't rely on the rendering context, you can submit your form results to /api/sitecore/{controllername}/{actionname}?country={values}&department={values} and get the data that way. (If you want an example of the kind of JS you need to do this I can provide one.) You could disable or hide the Department <select> until this is selected so that users don't get confused, then use the same technique to also set the Department parameter/submit that value. Once those two values are in the request, you have enough information to get a list or single Contact and display that information, also using the same technique.
If you have a more specific question about a particular aspect of this process I'd be happy to explain.

Fetch multiple values from same form

I have a form in which I am gathering information from the user. Based on the value of one of the dropdowns, I am showing a panel to the user. This panel contains textboxes, dropdowns etc.
Suppose the user fills in all the values, I want to show him an add more button. On clicking this button the value in the panel should be saved somewhere and the panel should go blank for adding more values. This way a user could enter values a number of times before the final submission. On final submission all these values would be saved to a table. Could somebody guide me with the methodology of how this could be achieved??
Also I want to know how this kind of thing can be achieved at the frontend?
You can either make use of Lists for this purpose or simple arrays.
You have not mentioned your fields clearly , but suppose they are, username, address, telephonenumber.
Then you can make list or dynamic arrays for each of these fields and on final submission, you can do Bulk Transfer to the database.
Link For Lists:
http://www.dotnetperls.com/list
Link For Bulk Insert:
http://blogs.msdn.com/b/nikhilsi/archive/2008/06/11/bulk-insert-into-sql-from-c-app.aspx
One way to do it, would be to use KnockoutJS where all adding/removing and UI manipulations are done by the library. Then submit JavaScript object as JSON to the server, serialize into objects and insert/update the database.

Javascript: Good practice to load all the data when the page loads?

I have a webpage in asp.net which uses editable grid to update/insert employee's records. A particular employee can have almost 50-70 attributes. Considering the frequent use of this page, I need to be very careful about the round trips to server and other I/O operations, as it might degrade the performance of page.
I am using a jquery plugin to choose from the given available columns. The left panel of listbox is populated using an xml file, which is read on server. The attributes are of multiple datatypes, such as simple string, integer or date.
The problem comes with the attributes which contain dropdown values, such as department, teams etc. Should I load the values of the dropdown values as the page loads in the start, irrespective of whether the user wishes to select the dropdowns or not? Or should I make another round trip to server and load the dropdown values of the selected attributes. Which approach should be used and why?
Note: There might be atmost 4 to 6 dropdown attributes, with maximum 30 to 40 values..
It really depends on both the odds of the user needing that dropdownlist, and how badly you'll want to avoid additional Ajax loads.
This is a very specific issue. But if your dropdownlist items won't really change on a per-item basis, I'd go with loading them during pageload. Else, if one employee's dropdownlist won't be the same as the other's, use Ajax so you can get a custom dropdownlist every time.
But like I said, very specific for your particular situation.

How to dynamically add a dataentry form in asp.net webforms

I have to create a data entry form in asp.net webforms where the user could enter several member details. Each member detail will have about twenty data items such as FirstName, Lastname, DateOfBirth etc. The number of members entered can be anywhere from one to say twenty.
Once all the members entered or during the entry process, they should be able to go to the previous or next entry and make changes. Essentially there should be a Next and Previous buttons which will traverse the pages. At the end when the Save button is clicked all the entered data should be saved.
I have created a UserControl, which has all the textboxes to enter data. I have created five hardcoded panels which display the usercontrol five times. This makes the total members that could entered as five.
I would like to replace this hardcoded model with a dynamically added panel, when the next button is clicked.
Please let me know how this could be achieved. Or if there is a better architecture please let me know. I tried the wizard control, but it was too cumbersome in maintaining the previously entered values and traversing data using Next and Previous buttons.
Thanks
You could add the controls dynamically to the page using:
Page.Controls.Add(new MyControl());
You'll have to find a temporary store for the data entered in the controls though such as Session.
Session["addedControls"] = myControls;
You can track the number of controls they add and then loop though and save all the data to whatever permanent store you're using.
There's an example of this here: http://howto.jamescarnley.com/2008/05/adding-fields-dynamically-in-aspnet.html
Storing the entire control in session does have it's drawbacks such as the overhead involved, you could just store the data which is more efficient but is a tiny bit more effort to implement.
This will also only work if they have cookies enabled.
Alternatively you could have a drop down list for them to select the number of entries they wish to make and display that number of controls by calling Page.Controls.Add the number of required times. Then just save them all in bulk at the end.
You could dynamically add the controls you need to input a new member easily enough in javascript. What you propose sounds like a nightmare to me. I'd put up a page with the controls to add a member and an 'Add Member' button. When the Add Member button is clicked - I would save the member to the database, retrieve a list of members added in this session - and display the names of the members in a list to the right of the 'Add Member' area of the page. If they want to review a member they can click on their name and you can show that member ready to be edited. Or they can add another member until they have finished. What you are trying to do is going to be a nightmare to manage and won't be any easier for the user to use.
Using dynamic controls will be very difficult and not user friendly as it may require refresh the page or using update panel
in your case, I would recommend doing it all from JavaScript using Knockout, This is a full sample Knockout Grid
Make sure after adding or editing the grid, you will serialize the JavaScript objects into string using JSON.Stringify and add this text to a hidden field.
On form submission, just get the hidden field value, use newtonsoft json library to convert the string into an object and fee free to use the object which will be a list of your model (ex: Order).
Compared to dynamic controllers, this is more manageable and user friendly

Sending collection of items in ASP.NET MVC

I've got two classes in my MVC project Order and Product.
Because Product can be ordered many times and Order can have many products I've got third entity which is OrderedProduct. It joins those two entities in many-to-many relation.
Now what I'm trying to do is to let user to make an order by putting products from the drop down list to the box and then to save my order. Also client have to fill some fileds in the Order entity such as Address data etc. All I want is to have it all on one single page. User can add as many items from dropdown as he like, then he can add whole order.
To make it easier to visualize look at this picture:
Now the problem is how to implement such behaviour in my MVC app. Should I build a ViewModel that combines Order class and list of Product or use partial view for Product classes?
Also which is my main problem, how can I (in elegant way) retrieve the full list of chosen products or at least product id's in the controller after POST request? In this case how can I specify that what I'm sending is a collection of ids? It's simple to add one object, but what about whole collection?
This is the place when I do not fully understand asp.net MVC, so please give me some bright ideas ;) Greetings to you all, thanks in advice for all your answers!
The desired interface seems a bit confusing to me but here's how you can handle these things.. modify to your desire. I'm going to assume OrderedProduct is an object for ordering that contains a Product ID and a quantity and that you want to be able to modify them all at the same time.
Make Order your ViewModel. Given that it has a List<OrderedProduct> property called OrderedProducts:
Create a small editor control with a ViewModel of OrderedProduct. No form, just a textbox/dropdown/whatever bound to the product name property and a textbox bound to the product quantity. Important: put this control in views/shared/EditorTemplates and call it OrderedProduct.ascx.
Give your Order object a property called NewOrderedProduct of type OrderedProduct.
In the form for the Order view do: <%=Html.EditorFor(m=>m.OrderedProducts)%> this will give you an editable list current items in the order.
After that do: <%= Html.EditorFor(m=> m.NewOrderedProduct) %> this is where you can add new items.
Have the [POST] action take a type of Order.
Now when it submits if the NewOrderedProduct property is valid you can add it to the OrderedProducts list and redisplay. You can add as many as you want this way and they will all autobind.
Have a separate submit button in the form for submitting the order. Check for the existence of that button's name in the [POST] and submit all at one time.
This gets you a straight HTML working version. From there you can Ajaxify it if you want.
Edit
Updated to reflect the function of the OrderedProduct object and correct the type the post accepts

Categories