Here I am trying to post a company view-model and update and insert according. But I feel I am writing it in wrong way or maybe there's a better approach.
Here's my code
[Route("Master/Company/Post"), HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> CompanyPostAsync(CompanyViewModel model)
{
model.CountryList = GetCountries();
//System.Threading.Thread.Sleep(3000);
var _viewName = "Companies";
if (!ModelState.IsValid)
return View(_viewName, model);
try
{
var find = await con.Companies.FirstOrDefaultAsync(x => x.ID == model.ID);
var currentUser = CurrentUser();
if (find != null)
{
find.Name = model.Name;
find.Alies = model.Alies;
find.Line1 = model.Line1;
find.Line2 = model.Line2;
find.City = model.City;
find.State = model.State;
find.CountryId = model.CountryId;
find.ZipCode = model.ZipCode;
find.POBoxNo = model.POBoxNo;
find.Telephone = model.Telephone;
find.Mobile = model.Mobile;
find.Email = model.Email;
find.Website = model.Website;
find.IncorporatedNumber = model.IncorporatedNumber;
find.IncorporatedDate = model.IncorporatedDate;
find.IsTaxApplicable = model.IsTaxApplicable;
find.IsLogoPrintInReport = model.IsLogoPrintInReport;
find.LogoPath = model.LogoPath;
find.IsActive = model.IsActive;
find.SaveCount += 1;
}
else
{
var company = new Company
{
Name = model.Name,
Alies = model.Alies,
Line1 = model.Line1,
Line2 = model.Line2,
City = model.City,
State = model.State,
CountryId = model.CountryId,
ZipCode = model.ZipCode,
POBoxNo = model.POBoxNo,
Telephone = model.Telephone,
Mobile = model.Mobile,
Email = model.Email,
Website = model.Website,
IncorporatedNumber = model.IncorporatedNumber,
IncorporatedDate = model.IncorporatedDate,
IsTaxApplicable = model.IsTaxApplicable,
IsLogoPrintInReport = model.IsLogoPrintInReport,
LogoPath = model.LogoPath,
IsActive = model.IsActive,
SaveCount = 1
};
con.Companies.Add(company);
}
await con.SaveChangesAsync();
CallSaved(true);
return RedirectToAction("Companies", "Master", new { id = find?.ID });
}
catch (Exception ex)
{
CallSaved(false, ex.Message);
return View(_viewName, model);
}
}