One of my views presents zero to many objects of four different entity classes.
My goal is to have an easy way to edit one common value for all four entity types.
There is only one submit button for the whole view, this submit button invokes an ActionResult where changes made to all editable values shall be stored like this (notice: this is not working because signature seems to be invalid):
public ActionResult SaveBloombergTickers(IEnumerable<StockPosition> stockpositions, IEnumerable<BondPosition> bondposition, ...)
{
if (ModelState.IsValid)
{
foreach (var stockposition in stockpositions)
{
db.Entry(stockposition).State = EntityState.Modified;
db.SaveChanges();
}
foreach (var bondposition in bondpositions)
{
db.Entry(bondposition).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View("Index");
}
Question 1: I kinda feel this is a stupid way to accomplish what I want. Unfortunatly, I am not aware of any "best practice" for this. Are you?
Question 2: What would a valid signature for the ActionResult in this case look like?
Solution (thanks to David L for giving me the idea):
1) Attach necessary data (ID of current element) to the textbox when building the View:
<input type="text" class="updateBloombergTicker StockPosition"
data-key="@stockposition.StockPositionID" style="width: 100px;"
value="@stockposition.BloombergID"/>
2) On textbox blur, fire corresponding Ajax-Event (I use a function "AJAX" for that) and hand over necessary info to controller:
$(".updateBloombergTicker").blur(function () {
$this = $(this);
if ($this.hasClass("StockPosition")) {
AJAX("../Excel/UpdateStockPositionTicker",
{
key: $this.attr("data-key"),
ticker: $this.val()
}
);
}
if ($this.hasClass("BondPosition")) {
.......
3) Controller does the rest:
[HttpPost]
public ActionResult UpdateStockPositionTicker(string key, string ticker)
{
if (ModelState.IsValid)
{
var stockposition = db.StockPositions.Find(Convert.ToInt32(key));
stockposition.BloombergID = ticker;
db.SaveChanges();
....