Reputation: 97
I have a form in which user enters the master details(Spending) first, and enters all the child details(SpendFor). I want to add another row where user can add next spendFor detail. But, I am really confused on how to do it. I know that I can use a partial view and add a new model(SpendFor) when user click on the Add button. But, once the user has finished adding all the "SpendFor" details, he will click on Save button. Now, how to retrieve all the details and SAVE.
This is my SpendingViewModel
public class SpendingViewModel
{
public Spending spending
{
get;
set;
}
public List<SpendFor> lstSpendFor
{
get;
set;
}
}
Spending class properties:-
int Id
int ItemId
int MemberId
float Amount
SpendFor class properties:-
int Id
int SpendingId
int SpendForId
int Quantity
float Amount
Upvotes: 0
Views: 250
Reputation: 4320
You can use FormCollection within receiving controller method to grab data from your form.
[HttpPost]
public void SaveData(FormCollection collection)
{
//Retrieve a single SpendingId value
var myValue = collection.Get["SpendingId"];
}
To grab values from a collection of your objects all you have to do is have your ListSpentFor objects have different Names. For example:
var count = 0;
foreach(var spentForItem in spentForItems)
{
//All fields will have different Ids and Names
<input id="spent-for-@count" name="spent-for-@count" type="text"/>
@count++;
}
Then inside of your Post controller method you can read that info off as:
[HttpPost]
public void SaveData(FormCollection collection)
{
//Loop through all input controls where names begin with spent-for-
foreach (var key in collection.AllKeys.Where(k => k.Contains("spent-for-")).ToArray<string>())
{
//Do whatever you need to do with pulled variable
var valueToDoSomethingWith = collection[key];
}
}
There are other ways. This is just one of them that I commonly use. Hopefully I didn't make any mistakes in code. I just typed it in directly here in notepad. Good luck.
Upvotes: 1