My model has a list property and in the view i need to be able to add an unlimited number of strings to it. So far it's not working and my lousy idea to make it work is the following: Each time a string is added, there's a postback. The new string is in the ViewModel's "newString" property (not a list). The HttpPost method will then save "newString" to the database, refill the list "allStrings" with all strings stored in the database and return the view with all strings and an emtpy textbox to add another string.
This is not a good solution for me because:
- There's a lot of postbacks if the user wants to add multiple strings
- If the user adds some strings to his item (a supplier), all these strings are saved to the database. When he then decides he doesn't want to save the supplier all the stored strings are useless and need to be deleted from the database.
I have not implemented this because I know there's far better solutions and I just don't find them. This is what I have:
The ViewModel:
public class SupplierViewModel
{
public Supplier Supplier { get; set; }
public List<string> allStrings;
public string newString { get; set; }
}
The Controller:
[HttpPost]
public ActionResult Create(SupplierViewModel model)
{
model.allStrings.Add(model.newString);
if (ModelState.IsValid && model.newString == "")
db.Suppliers.Add(model.Supplier);
db.SaveChanges();
return RedirectToAction("Index");
}
model.newString = "";
return View(model);
}
The View:
<div class="editor-label">
@Html.LabelFor(model => model.allStrings)
</div>
@for (int i = 0; i < Model.allStrings.Count; i++)
{
<div class="editor-label">
@Html.EditorFor(model => model.allStrings[i])
</div>
}
<div class="editor-label">
@Html.EditorFor(model => model.newString)
</div>
Note that in this implemented version, none of the strings are saved to the database and the list is cleared after each postback. Only one string (the last one added) is displayed on the view.
Basically the question is: How can I have the user add as many strings as he wants with as few postbacks and database-interaction as possible?
Thanks in advance