I need to read a List that has two properties, one is an ID int, the other is string.
After I get the values into the list I don't know how to break them down to the the IDs and name string one by one.
This is what I've got:
private async void UpdatePisterosLocal(List<Pisteros> PisterosLista)
{
try
{
PisterosDBController pistDB = new PisterosDBController();
Pisteros_Local pistLocal = new Pisteros_Local();
//this is my code trying to read the list PisterosLista
foreach (string element in PisterosLista)
{
pistLocal.IDPistero = //don't know what to write here
pistLocal.PisteroN = //and here
}
}
catch (Exception ex)
{
throw ex;
}
}
This how I finally did it
foreach (var item in PisterosLista)
{
var DatosRegistro = new T_Pisteros
{
PisteroID = item.PisteroID,
PisteroN = item.PisteroN
};
var num = db.Insert(DatosRegistro); //insert into new DB
}
Hello I have a controller method that I want to return the view model of that looks like this
This is what it would look like if it was hard-coded
public ActionResult SpecialOrderSummary(int? id)
{
// Retrieve data from persistence storage and save it to the view model.
// But here I am just faking it.
var vm = new ItemViewModel
{
ItemId = 123,
ItemName = "Fake Item",
Parts = new List<ItemPartViewModel>
{
new ItemPartViewModel
{
PartId = 1,
PartName = "Part 1"
},
new ItemPartViewModel
{
PartId = 2,
PartName = "Part 2"
}
}
};
return View(vm);
}
But I obviously don't want it hard coded. So this is what I was trying to do instead to achieve my goal
public ActionResult SpecialOrderSummary(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobOrder jobOrder = db.JobOrders.Find(id);
if (jobOrder == null)
{
return HttpNotFound();
}
ViewBag.JobOrderID = jobOrder.ID;
ItemInstance ii = db.ItemInstances.Where(x => x.serialNumber == jobOrder.serialNumber).FirstOrDefault();
Item item = db.Items.Find(ii.ItemID);
var vm = new ItemViewModel
{
ItemId = item.ItemID,
ItemName = item.Name,
Parts = new List<ItemPartViewModel>
{
foreach(ItemHasParts ihp in item.IHP)
{
Part part = db.Parts.Find(ihp.PartID);
new ItemPartViewModel
{
PartId = part.ID,
PartName = part.Name
};
}
}
};
return View(vm);
}
But that doesn't work. As it doesn't seem to recognize the closing }
of the opening "Parts" and the opening "vm" bracket as it skips both. Why is this?
Hmmm I thought I answered this question before: https://stackoverflow.com/a/62782124/2410655. Basically you can't have a for loop like that in the middle of the view model.
I would like to add 2 more things to it.
1. Id?
If the special order summary expects an ID, don't declare it as optional. If you do so, you have to add more logic to check whether there is an ID or not.
If the order summary expects an ID, just declare it as int id. And if the client doesn't provide it, let the MVC framework handle the error. Now depending on your setup, your MVC might throw a 404, or 500, or a user-friendly page. It's up to you, the developer, to set it up.
2. Be careful on NullReference Exception
In your code example, I see you used FirstOrDefault() on the item instance. That will bite you if it comes back as NULL and you call db.Items.Find(ii.ItemID)...
So based on your example, I would change the code to:
public ActionResult SpecialOrderSummary(int id)
{
JObOrder jobOrder = db.JobOrders.Find(id);
if (jobOrder == null)
{
return HttpNotFound();
}
ItemInstance itemInstance = db.ItemInstances
.Where(x => x.serialNumber == jobOrder.serialNumber)
.FirstOrDefault();
Item item = null;
if (itemInstance != null)
{
item = db.Items.Find(itemInstance.ItemID);
}
var vm = new JobOrderSummaryViewModel
{
JobOrderId = jobOrder.ID,
Parts = new List<ItemPartViewModel>();
};
if (item != null)
{
vm.ItemId = item.ItemId;
vm.ItemName = item.ItemName;
foreach(ItemHasParts ihp in item.IHP)
{
// Does Part and Item have many-to-many relationships?
// If so, you might be able to get the part by
// ihp.Part instead of looking it up using the ID.
// Again, it depends on your setup.
Part part = db.Parts.Find(ihp.PartID);
if (part != null)
{
vm.Parts.Add(new ItemPartViewModel
{
PartId = part.ID,
PartName = part.Name
});
}
}
}
return View(vm);
}
Note:
You have additional calls back to the database inside the loop (db.Parts.Find(ihp.PartID);). That will cause performance issue if you have huge data. Is there any way you can fetch all your data you needed once at the beginning?
Below is my controller That I am calling from a href button and passing an id. The href button is a duplicate button which is meant to create a copy of the selected module and add it to the database and then return it.
public ActionResult dupe(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
MODULE Modules = db.MODULE.Find(id);
if (Modules == null)
{
return HttpNotFound();
}
else
{
MODULE newMOd = new MODULE();
newMOd.APPLY__FINISH = Modules.APPLY__FINISH;
newMOd.CREATED_BY = Modules.CREATED_BY;
newMOd.CREATED_DATE = Modules.CREATED_DATE;
newMOd.MODULE_DESC = "Duplicate-"+Modules.MODULE_DESC;
newMOd.MODULE_TYPE = Modules.MODULE_TYPE;
newMOd.MODULE_TYPE1 = Modules.MODULE_TYPE1;
newMOd.PRODUCT_LINE = Modules.PRODUCT_LINE;
newMOd.MODULE_NAME = "Duplicate-" + Modules.MODULE_NAME;
foreach (MODULE_PARTS mp in Modules.MODULE_PARTS)
{
newMOd.MODULE_PARTS.Add(mp);
}
foreach (MODULE_OPTION mo in Modules.MODULE_OPTION)
{
MODULE_OPTION m = new MODULE_OPTION();
m.OPTION_NAME = mo.OPTION_NAME;
m.OPTION_TYPE = mo.OPTION_TYPE;
m.PRODUCT_LINE = mo.PRODUCT_LINE;
m.ADDED_BY = mo.ADDED_BY;
m.ADDED_ON = mo.ADDED_ON;
m.DEFAULT_FACTOR = mo.DEFAULT_FACTOR;
foreach (OPTION_PARTS op in mo.OPTION_PARTS)
{
m.OPTION_PARTS.Add(op);
}
newMOd.MODULE_OPTION.Add(mo);
}
newMOd.MODULE_PARTS = Modules.MODULE_PARTS;
newMOd.MODULE_OPTION = Modules.MODULE_OPTION;
db.MODULE.Add(newMOd);
db.SaveChanges();
}
return View(Modules);
}
This is my controller method, and when I try to add this module to database I get collection modified error. I'm not sure how or where?
enter image description here
The exception message in this case is quite clear... you cannot modify a member of a collection you are currently iterating over. It's that simple.
Hi i am building a web application for school.
I am trying to update student information, i already did teacher part
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Teacher teacher)
{
if (!ModelState.IsValid)
{
var data = teacher;
return View("TeacherForm", data);
}
if (teacher.Id == 0)
_context.Teachers.Add(teacher);
else
{
var dataInDb = _context.Teachers.Single(c => c.Id == teacher.Id);
dataInDb.Name = teacher.Name;
dataInDb.Designation = teacher.Designation;
dataInDb.EducationalQualification = teacher.EducationalQualification;
dataInDb.DateOfBirth = teacher.DateOfBirth;
dataInDb.PhoneNumber = teacher.PhoneNumber;
dataInDb.StartDate = teacher.StartDate;
dataInDb.EndDate = teacher.EndDate;
dataInDb.Status = teacher.Status;
}
_context.SaveChanges();
return RedirectToAction("Index", "Teacher");
}
But in Student part i want to use auto mapper for map data
if (student.Id == 0)
_context.Students.Add(student);
else
{
var dataInDb = _context.Students.Single(c => c.Id == student.Id);
Mapper.Map(student, dataInDb);
}
but its not working. I try to edit data but the table data remain same.
its relay difficult to write every property for student.
how can i solve this problem?
A bit of background to my issue - I've inherited a large C# MVC application, and I'm currently making a change to the main process in the app.
So originally, the user would upload an item, and that would be that. Now however, the user can select a checkbox in order to have the item delivered. If this checkbox is selected, the Delivery table is populated with the relevant details.
Here is the POST action in my Items controller for when the user originally uploads the item details:
[HttpPost]
public ActionResult AddItemDetails(Int64? itemId, Item item, FormCollection formValues)
{
if (formValues["cancelButton"] != null)
{
return RedirectToAction("Index");
}
if (formValues["backButton"] != null)
{
return RedirectToAction("AddItemStart");
}
string ImageGuid = formValues["ImageGUID"];
ViewData["Image_GUID"] = ImageGuid;
if (item.ImageID == null && String.IsNullOrEmpty(ImageGuid))
{
ModelState.AddModelError("Image", "Image is required.");
ViewData["Image"] = "Image is required.";
}
if (ModelState.IsValid)
{
item.SubmissionState = -1; // Unsubmitted;
/**********************ADDED 25/1/2011**************************/
item.ProductCode = formValues["ProductCode"];
item.Name = formValues["Name"];
string deliverySelection = formValues["deliverySelection"];
if (deliverySelection == "on")
{
item.DeliverySelection = "Yes";
Delivery c = new Delivery()
{
ProductCode = formValues["ProductCode"],
Name = formValues["Name"],
PhoneNo = formValues["PhoneNo"],
Address = formValues["Address"],
SubmissionDate = System.DateTime.Now
};
item.Delivery = c;
}
else
{
item.DeliverySelection = "No";
}
/*****************************END*******************************/
if (itemId.HasValue)
{
UpdateItemDetails(item, ImageGuid, this);
}
else
{
titleId = ItemServices.AddItem(item, ImageGuid);
}
return RedirectToAction("AddSubItemDetails", new { itemId = item.ItemID });
}
return View(item);
}
This works fine, and achieves the desired result. However, I am a little stuck on modifying the update action for in the Items controller. Here is what I have so far:
[HttpPost]
public ActionResult UpdateItemDetails(Int64 itemId, Item item, FormCollection formValues)
{
if (formValues["cancelButton"] != null)
{
return RedirectToAction("View", new { itemId = itemId });
}
string image = formValues["ImageGUID"];
ViewData["Image_GUID"] = ImageGuid;
if (item.ImageID == null && String.IsNullOrEmpty(ImageGuid))
{
ModelState.AddModelError("Image", "Image is required.");
}
if (ModelState.IsValid)
{
//**********************Added 31.01.2011****************************//
using (ModelContainer ctn = new ModelContainer())
{
string DeliverySelection = formValues["deliverySelection"];
if (deliverySelection == "on")
{
item.DeliverySelection = "Yes";
Delivery c = new Delivery()
{
ProductCode = formValues["ProductCode"],
Name = formValues["Name"],
PhoneNo = formValues["PhoneNo"],
Address = formValues["Address"],
SubmissionDate = System.DateTime.Now
};
ctn.Delierys.AddObject(c);
item.Delivery = c;
}
else
{
item.DeliverySelection = "No";
}
ctn.AddToItems(item);
ctn.SaveChanges();
UpdateItemDetails(item, ImageGuid, this);
return RedirectToAction("View", new { itemId = itemId });
}
return View("UpdateItemDetails", MasterPage, item);
}
Notice how this is slightly different and uses the UpdateItemDetails() to update the database. I was unsure what to do here as I do need to collect formvalues to insert into the Delivery database. Here is UpdateItemDetails:
private void UpdateItemDetails(Item item, string ImageFileGuid, ItemsController controller)
{
using (ModelContainer ctn = new ModelContainer())
{
Item existingData = ItemServices.GetCurrentUserItem(item.ItemID, ctn);
controller.UpdateModel(existingData);
existingData.UpdatedBy = UserServices.GetCurrentUSer().UserID;
existingData.UpdatedDate = DateTime.Now;
// If there is a value in this field, then the user has opted to upload
// a new cover.
//
if (!String.IsNullOrEmpty(ImageFileGuid))
{
// Create a new CoverImage object.
//
byte[] imageBytes = FileServices.GetBytesForFileGuid(Guid.Parse(ImageFileGuid));
Image newImage = new Image()
{
OriginalCLOB = imageBytes,
ThumbnailCLOB = ImageServices.CreateThumbnailFromOriginal(imageBytes),
HeaderCLOB = ImageServices.CreateHeaderFromOriginal(imageBytes),
FileName = "CoverImage"
};
existingData.Image = newImage;
}
ctn.SaveChanges();
}
}
The code working as above, throws the following error when I try to update the details:
System.Data.SqlClient.SqlException:
The conversion of a datetime2 data
type to a datetime data type resulted
in an out-of-range value. The
statement has been terminated.
This error is thrown at ctn.SaveChanges() in the update action.
So I suppose my first question is how to overcome this error, however without making changes that will affect the AddItemDetails action. My second question then would be, if that error was cleared up, would this be a correct way to go about updating?
I'd be very grateful for any pointers. If any more info is needed, just ask.
Thanks :)
I was looking into your error and found this answer to another question that gives a little more information about the DATETIME and DATETIME2 data types.
DATETIME supports 1753/1/1 to
"eternity" (9999/12/31), while
DATETIME2 support 0001/1/1 through
eternity.
If you check the data that is being submitted do you see anything anomalous? Do you have a date property in your item class that is being set to some default value that is invalid for the DATETIME field?
It looks like one of the dates in the object you are trying to save is DateTime.MinValue. It could be the submission date for example. Check your form data to see if the value is being updated ofmr the client correctly and go from there.
I have this issue currently because if someone mistakenly forgets a slash (e.g. 1/189 when they meant 1/1/89), TryUpdateModel() updates the model without error, translating it to the .NET DateTime of "1/1/0189".
But then the Save crashes with the "conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value".
So wow do I catch this before the Save?