Gavin5511
Gavin5511

Reputation: 791

Best way to pass back error info from a model?

I have a service which is called from my controller to upload images. This works well, but when criteria is not met, it currently returns 'null' which is not helpful or elegant. Current code is:

    public async Task<string> UploadPropertyImageAsync(HttpPostedFileBase imageToUpload)
    {
        string imageFullPath = null;
        if (imageToUpload == null || imageToUpload.ContentLength == 0 || imageToUpload.ContentLength >= 8388608)
        {
            return null;
        }

        WebImage img = new WebImage(imageToUpload.InputStream);
        if (img.Width < 1000)
        {
            return null;
        }    

        try
        {
            //Do Something
        }
        catch (Exception ex)
        {
            //Log something
        }
        return imageFullPath;
    }
}

I have tried passing ViewBag and TempData back, but neither seems to be valid code? How can I write an error message string and pass it back to a view?

Adding controller method

    [HttpPost]
    public async Task<ActionResult> Upload([Bind(Include = "ID,Caption")] HttpPostedFileBase photo, PropertyImage image, int propertyId)
    {
        var imageUrl = await imageService.UploadPropertyImageAsync(photo);
        var imageGuid = Guid.NewGuid();
        image.Original_URL = imageUrl.ToString();
        image.PropertyID = propertyId;
        image.DateCreated = DateTime.Now;
        image.ID = imageGuid;
        image.Status = true;
        db.PropertyImage.Add(image);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

Upvotes: 0

Views: 86

Answers (2)

Haitham Shaddad
Haitham Shaddad

Reputation: 4456

Your action should return Task<ActionResult> if it is an MVC application or Task<IHttpActionResult> if it was a web API.

In your code, if the criteria is not met, then return a Bad Request, using the return BadRequest() helper method which exist in both Controller and ApiController classes. You can also include additional information in the request body.

So, your code should be like this:

[HttpPost]
    public async Task<ActionResult> Upload([Bind(Include = "ID,Caption")] HttpPostedFileBase photo, PropertyImage image, int propertyId)
    {
        var imageUrl = await imageService.UploadPropertyImageAsync(photo);
        if(imageUrl == null)  
           return BadRequest();
        else
        {
         var imageGuid = Guid.NewGuid();
         image.Original_URL = imageUrl.ToString();
         image.PropertyID = propertyId;
         image.DateCreated = DateTime.Now;
         image.ID = imageGuid;
         image.Status = true;
         db.PropertyImage.Add(image);
         await db.SaveChangesAsync();
         return RedirectToAction("Index");
        }
    }


   public async Task<IHttpActionResult> UploadPropertyImageAsync(HttpPostedFileBase imageToUpload)
    {
        string imageFullPath = null;
        if (imageToUpload == null || imageToUpload.ContentLength == 0 || imageToUpload.ContentLength >= 8388608)
        {
            return null;
        }

        WebImage img = new WebImage(imageToUpload.InputStream);
        if (img.Width < 1000)
        {
            return null;
        }    

        try
        {
            //Do Something
        }
        catch (Exception ex)
        {
            //Log something
        }
        return  imageFullPath;
    }
}

Upvotes: 1

KevDevMan
KevDevMan

Reputation: 818

Your task is returning a string!

So you could do something like

if (imageToUpload == null || imageToUpload.ContentLength == 0 || imageToUpload.ContentLength >= 8388608)
{
            return "MY_ERROR_STRING";
}

Not the best way at all

My advice would be to return an simple object

public class ResultObj(){
  public bool Success {get;set;};
  public string Result {get;set;};
}

then test for success, if true the result is the path, if false, its your error message. so your code would look like

 public async Task<ResultObj> UploadPropertyImageAsync(HttpPostedFileBase imageToUpload)
    {
        ResultObj result = null;
        if (imageToUpload == null || imageToUpload.ContentLength == 0 || imageToUpload.ContentLength >= 8388608)
        {
            result.Success= False;
            result.Result = "We have error" ;
            return result;
        }

        WebImage img = new WebImage(imageToUpload.InputStream);
        if (img.Width < 1000)
        {
            result.Success= False;
            result.Result = "We have a different error" ;
            return result;
        }    

        try
        {
            //Do Something
        }
        catch (Exception ex)
        {
            //Log something
        }
        result.Success= true;
        result.Result = imageFullPath;
        return result;
    }   

Upvotes: 0

Related Questions