【问题标题】:How to check HttpPostedFileBase is not null ? [duplicate]如何检查 HttpPostedFileBase 不为空? [复制]
【发布时间】:2018-09-11 16:42:08
【问题描述】:

我的 ViewModel 包含以下 2 个属性:

[DataType(DataType.Upload)]
public HttpPostedFileBase ImageFile { get; set; }
[DataType(DataType.Upload)]
public  HttpPostedFileBase AttachmentFile { get; set; }

我的视图是这样写的:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "product-master-form", enctype = "multipart/form-data" }))
{
  //some html and razor is written here. 
  <div id="attachments" class="tab-pane fade">
   @Html.TextBoxFor(model => model.AttachmentFile, new { type = "file" })
 </div><!--/close attachements pane-->
 <div id="product-image-up" class="tab-pane fade">
   @Html.TextBoxFor(model => model.ImageFile, new { type = "file" })
 </div><!--/close panel for image upload-->
}

我的控制器目前看起来像这样:

if(masterViewModel.ImageFile.ContentLength != 0)
{

 if(masterViewModel.ImageFile.ContentLength > imageSizeLimit)
 {
   otherErrorMessages.Add("Image size cannote be more than " + readableImageSizeLimit);
 }
 if (!validImageTypes.Contains(masterViewModel.ImageFile.ContentType))
 {
   otherErrorMessages.Add("Please choose either a GIF, JPG or PNG image.");
 }
 try
 {
   //code to save file in hard disk is written here. 
 }catch(Exception ex)
 {
  otherErrorMessages.Add("Cannot upload image file: "+ ex);
 }


}//end block for handling images. 

我的问题出在控制器上,如何检查图像文件是否为空?当我提交表格时,图像文件不是必须填写在表格内的字段。当我提交没有图像文件的表单时,代码执行到达该行:if(masterViewModel.ImageFile.ContentLength != 0)

它会抛出一个异常声明:object reference not set to an instance of an object。但是,如果我提交带有图像文件的表单,程序将继续正常执行。

提前谢谢你。

【问题讨论】:

标签: c# asp.net asp.net-mvc


【解决方案1】:

为什么不使用空条件运算符?:

if(masterViewModel?.ImageFile?.ContentLength != 0)

这样,如果masterViewModelImageFileContentLength 为空,它将短路并返回空。那么null不等于0所以会返回false。

否则你可以写:

if (masterViewModel != null && masterViewModel.ImageFile != null && masterViewModel.ImageFile.ContentLength != 0)

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 2015-06-14
    • 2011-07-02
    • 2018-07-03
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多