从Excel导入应用程序,然后使用asp.net mvc和wcf保存在数据库中。 由于空字段,它会生成错误。我检查了我的数据库和我的代码,我看到我在那些字段中允许null
请参阅下面的控制器。
控制器
public ActionResult ImportCacExcel(HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
var bodsList = new List<CAC>();
if (FileUpload != null)
{
HttpPostedFileBase file = Request.Files["FileUpload"];
if (true)//FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
// if(currentSheet.Count)
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var bod = new CAC();
bod.RC_NUMBER = workSheet.Cells[rowIterator, 1].Value.ToString();//.ToString().Trim();
bod.COMPANY_NAME = workSheet.Cells[rowIterator, 2].Value.ToString();//.ToString().Trim();
bod.OWNERSHIP_STRUCTURE = workSheet.Cells[rowIterator, 3].Value.ToString();//.ToString().Trim();
bod.ADDRESS_STREET = workSheet.Cells[rowIterator, 4].Value.ToString();
bod.ADDRESS_CITY = workSheet.Cells[rowIterator, 5].Value.ToString();
bod.ADDRESS_STATE = workSheet.Cells[rowIterator, 6].Value.ToString();
bod.ADDRESS_PMB = workSheet.Cells[rowIterator, 7].Value.ToString();
bod.ADDRESS_POBOX = workSheet.Cells[rowIterator, 8].Value.ToString();
bod.ADDRESS_LGA = workSheet.Cells[rowIterator, 9].Value.ToString();
try
{
bod.DATE_OF_REGISTRATION = Convert.ToDateTime("01/01/" + workSheet.Cells[rowIterator, 4].Value);//.ToString().Trim();
}
catch (Exception e)
{
data.Add("Bad Date format for item at row " + rowIterator);
}
bod.ACTION_STATUS = 1;
bod.CREATED_DATE = DateTime.Now;
bodsList.Add(bod);
}
}
foreach (var item in bodsList)
{
_cacService.AddCac(item);
}
return RedirectToAction("Index");
}
else
{
data.Add("<ul>");
data.Add("<li>Only Excel file format is allowed</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
data.Add("<ul>");
if (FileUpload == null) data.Add("<li>Please choose Excel file</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
如果像
这样的字段,请如何更改控制器中的代码以ckeck为空或空,应向用户指示。 但如果像
这样的字段为null或为空,它应该向excel添加null,并将null保存到数据库。
答案 0 :(得分:1)
要应用用户输入验证,因此不允许空值传递。客户端验证,例如使用javascript将是最好的。这可以防止发布表单。这还必须包括控制器中的服务器端验证,以防止客户端验证失败,从而防止程序错误。
if(String.IsNullOrWhiteSpace(workSheet.Cells[rowIterator, 1].Value.ToString())
{
// Do something to prevent form submission.
}
else
{
bod.RC_NUMBER = workSheet.Cells[rowIterator, 1].Value.ToString();
}
对于允许为null的所有值。将它们初始化为null可能更简单。然后检查值是否确实为空,如果它们不是,则将该值赋给CAC
属性。
bod.ADDRESS_STREET = null;
if(!String.IsNullOrWhiteSpace(workSheet.Cells[rowIterator, 1].Value.ToString())
{
bod.ADDRESS_STREET = workSheet.Cells[rowIterator, 4].Value.ToString();
}