Craig
Craig

Reputation: 18694

Asp.net MVC - Variable amount of entries

I have a view where a user can enter a bank transaction. So they select an Account, a Payee, a Category (Based on allowable categories for the selected Payee) and a Sub Category (based on the Category selection) - and a value. This is done via JQuery, and is working.

However, there is a requirement to select more than one category/subcategory/amount per transaction (Split the transaction).

I'd like to maybe add a 'grid' (So, a table), and a button under the category/sub category/amount section, labelled 'Add', which then adds the selected Cat/SubCat/Amount to a grid, then blanks the existing selections, ready for more to be added - allowing the user to add as many 'amounts' as needed.

But - how?

On the Add button, I guess I would need to add the CategoryId, SubCategoryId and Amount to a List<>? Then based on that list, build the summary grid?

I'd like there to be no flashing of the screen. Would this have to be done via JQuery? Build the table with JQuery, and then have the list of cats/subcats/amounts sent back to the server on Form submittion?

Upvotes: 0

Views: 150

Answers (1)

Gideon
Gideon

Reputation: 18491

You might want to look into the jQuery tmpl plugin. This plugins allows you to build client side templates. This is the kind of thing you might want to use on your site.

You define one template of a table row, and each time just add a new row based on that template. I would give each form item in the table row an extra index variable (such as name="CategoryID-1" for the first row). While inserting a new row, you just send the current index to the template, and make sure the template adds the current index to the names of the form elements.

Then on the server side, you can do a simple query to get all the indeces.

ie

int[] indices = Request.Form.AllKeys.Where(k => k.StartsWith("CategoryID-")).Select(k => Convert.ToInt32(k.Substring(11))).ToArray();

foreach (int index in indices)
{
    string cat = Request.Form["CategoryID-" + index.ToString()];
    string subcat = Request.Form["SubCategoryID-" + index.ToString()];
    //etc.

}

Upvotes: 1

Related Questions