I am working on an ASP.Net core application and would like to align some text in a string.
Somehow I am not able to get this working and am probably missing something very obvious here.
So this is my code (simplified):
public class AdminController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ImportOrganizations(ICollection<IFormFile> files)
{
var count = 0;
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
foreach (var file in files)
{
if (file.Length <= 0) continue;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var csv = new CsvReader(reader);
while (csv.Read())
{
// Fields that need to be filled
string name;
try
{
name = csv.GetField<string>("Name");
}
catch (Exception ex)
{
ModelState.AddModelError("", $"Row {csv.Row, 10}, {ex.Message}");
continue;
}
// Check if name has a value
if (string.IsNullOrWhiteSpace(name))
{
ModelState.AddModelError("", $"Row {csv.Row, 10}, Name is a required field");
continue;
}
if (await _context.Organizations.AnyAsync(o => o.Name == name))
{
ModelState.AddModelError("", $"Row {csv.Row, 3}, Organization {name} already exists");
continue;
}
// Add the new Event
var or = new Organization()
{
Name = name
};
_context.Organizations.Add(or);
}
await SaveContext();
}
}
var model = new ImportViewModel("Import Organizations", nameof(ImportOrganizations), count);
return View("Import", model);
}
}
Now when the import file does not have a value in the name field, I expect something like this in my browser:
Row 20 , Name is a required field
But I keep getting this:
Row 20, Name is a required field
Could someone help me out here?