简体   繁体   中英

MVC + returning different PartialView on condition

Not sure if this is the best approach in MVC but how do I return views on condition, let's say if I want to return another view which displays some error message if my 'fbUID' is missing, please kindly assist. Thanks.

public PartialViewResult GetCredentials(string facebookUID, string facebookAccessTok)
{
    string fbUID = facebookUID;

    if (fbUID != null)
    {
        // Request fb profile pic
        var rawImg = new Bitmap(ImageHelper.requestBitmapImage(fbUID));
        var processblurredImg = new Bitmap(rawImg);

        var gb = new GaussianBlur();

        for (int i = 0; i < 8; i++)
        {
            gb.ApplyInPlace(processblurredImg);
        }

        // Download it to local drive / server
        string uploadPath = Server.MapPath("~/upload");
        string fullPath = uploadPath + "\\ProfilePic.png";

        if (!Directory.Exists(uploadPath))
        {
            Directory.CreateDirectory(uploadPath);
        }
        if (uploadPath != null)
        {
            ImageHelper.savePng(fullPath, processblurredImg, 500L);
        }

        return PartialView("BlurredPhoto");
    }
    return PartialView("TestPartialView"); //if fbUID is null
}

Have a look at action filters. These allow you to install a class via an attribute on your controller method which intercepts the call before your method runs. You can do this kind of basic checking here and return a standard error handler result from here.

ASP.NET MVC has a built-in HandleErrorFilterAttribute that helps you to return error views if some errors occured in action or other filters. The built-in HandleError filter returns view not a partial view so you may have to create a custom one to return a partial view. The idea is you have to throw some custom exception from your action if fbUID is null and the custom handle error filter returns a partial view if it handles that exception.

I suggest going for a custom handle error filter approach only if you see this functionality in many places else it's more work for a simple thing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM