Serkan Yıldırım
Serkan Yıldırım

Reputation: 125

How can get nullable string value?

[HttpGet]
public ActionResult Login(string? returnUrl)
{
    if (Request.IsAuthenticated)
    {
        if(returnUrl.HasValue)
           return RedirectToAction("Index", "Home");
        else
           return RedirectToAction(returnUrl);
    }
    return View();
}

enter image description here

Error: The best overloaded method match for 'System.Web.Mbv.Controller.Redirect(string)' has some invalid arguments

How can use nullable string for RedirectToAction()

Upvotes: 2

Views: 1867

Answers (1)

Stephen Brickner
Stephen Brickner

Reputation: 2602

String is nullable already but you can check for null with string.IsNullOrEmpty.

[HttpGet]
public ActionResult Login(string returnUrl)
{
        if (Request.IsAuthenticated)
        {
           if(string.IsNullOrEmpty(returnUrl))
           {
               return RedirectToAction("Index", "Home");
           }
           else
           {
               return RedirectToAction(returnUrl);
           }
        }
        return View();
}

You could also default it so if it's not passed in it will never be empty.

[HttpGet]
    public ActionResult Login(string returnUrl = "www.yourDomain.com/login")
    {
            if (Request.IsAuthenticated)
            {
               return RedirectToAction(returnUrl);
            }
            return View();
    }

Upvotes: 7

Related Questions