Contoh fungsi validasi ketika meng-import file excel berisi banyak data manufacturer
[code language=”csharp”]
[HttpPost]
public ActionResult Process(ManufacturerModel model)
{
if (ModelState.IsValid)
{
//kamus
List<ValidationResult> results = new List<ValidationResult>();
List<string> errList = new List<string>();
List<ManufacturerFormStub> list = model.Parse();
List<ManufacturerCategoryFormStub> listCategory = model.ParseCategory();
manufacturer manufacturer;
//algoritma
for (int i = 0; i < list.Count; ++i)
{
results.Clear();
Validator.TryValidateObject(list[i], new ValidationContext(list[i], null, null), results, true);
if (TryValidateModel(list[i]))
{
manufacturer = list[i].GetManufacturer();
RepoManufacturer.Save(manufacturer);
errList.Add("Baris ke-" + (i + 1) + " (" + list[i].Name + ") berhasil disimpan");
//save class &category
foreach (ManufacturerCategoryFormStub categoryForm in listCategory)
{
categoryForm.ManufacturerId = manufacturer.id;
RepoManufacturer.SaveManufacturerCategory(categoryForm.GetManufacturerCategory());
}
}
else
{
string err = "Baris ke-" + (i + 1) + " gagal disimpan (";
for (int j = 0; j < results.Count; ++j )
{
err += results[j].ToString() + ((j == results.Count – 1) ? ")" : " ");
}
errList.Add(err);
ModelState.Clear();
}
}
foreach (string s in errList)
{
ModelState.AddModelError(string.Empty, s);
}
return View("Import", new ManufacturerModel());
}
else
{
return View("Import", model);
}
}
[/code]