0

My ViewModel contains these 2 properties:

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

My View is written like this:

@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-->
}

My controller currently looks like this:

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. 

My problem is in the controller, how I do check if the image file is null or not null ? When I submit the form, the image file is not a compulsry field to fill inside the form. When I submit the form without a image file, and the code execution reaches the line : if(masterViewModel.ImageFile.ContentLength != 0)

it will throw an exception stating : object reference not set to an instance of an object. However, if I submit the form with the image file, the program will continue execution normally.

Thank you in advance.

JC6T
  • 135
  • 4
  • 13
  • 1
    Apparently you check if `masterViewModel.ImageFile == null`? – GSerg Sep 11 '18 at 08:41
  • 1
    Not related, but ou might also want to look at using validation attributes for client and server side validation of you file type and size (refer [How to validate file type of HttpPostedFileBase attribute?](https://stackoverflow.com/questions/40199870/how-to-validate-file-type-of-httppostedfilebase-attribute-in-asp-net-mvc-4/40200034#40200034) –  Sep 11 '18 at 08:43

1 Answers1

1

Why not use the null conditional operator?:

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

That way it will short-circuit and return null if masterViewModel, ImageFile, or ContentLength is null. Then null isn't equal to 0 so it will return false.

Otherwise you could write:

if (masterViewModel != null && masterViewModel.ImageFile != null && masterViewModel.ImageFile.ContentLength != 0)
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86