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.