Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Not all code paths return a value" when returning View in MVC

I want to return a view if an object(country) is not null. But I get the error "Not All code paths return a value"

My code looks like this

public ActionResult Show(int id)
{
    if (id != null)
    {
        var CountryId = new SqlParameter("@CountryId", id);
        Country country = MyRepository.Get<Country>("Select * from country where CountryId=@CountryId", CountryId);
        if (country != null)
        {
            return View(country);
        }
    }

}
like image 905
Lucy Avatar asked May 03 '26 12:05

Lucy


1 Answers

This happens when you are returning something from within the "if" statement. The compiler thinks, what if the "if" condition is false? That way you are not returning anything even when you have the return type of "ActionResult" defined in the function. So add some default returns in the else statement:

public ActionResult Show(int id)
{

    if (id != null)
    {
        var CountryId = new SqlParameter("@CountryId", id);
        Country country = MyRepository.Get<Country>("Select * from country where CountryId=@CountryId", CountryId);

        if (country != null)
        {
            return View(country);
        }
        else
        {
            return View(something);
        }
    }
    else
    {
        return View(something);
    }
}
like image 122
Captain Red Avatar answered May 05 '26 03:05

Captain Red



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!