Nullable

Posted on:

A method

The details

In ASP.NET Core MVC, action methods are used to handle HTTP requests and generate HTTP responses. Sometimes, an action method may have a nullable parameter, which means that the parameter can be null. In this article, we’ll see how to allow a null parameter in an action method, and how to redirect to a page when the parameter is null.

Let’s consider the following example, where we have an action method that handles HTTP POST requests for a “Donor” page:

[HttpPost]
public IActionResult Donor(string donorName)
{
HttpContext.Session.SetString("DonorName", donorName);
return RedirectToAction("Description");
}

Here, the action method expects a non-null donorName parameter, which is then stored in a session variable before redirecting to the “Description” page. However, if the donorName parameter is null, an exception will be thrown, which is not desirable.

To allow the donorName parameter to be null, we can use the Nullable keyword in the parameter declaration:

[HttpPost]
public IActionResult Donor(string? donorName)
{
HttpContext.Session.SetString("DonorName", donorName ?? "");
return RedirectToAction("Description");
}

Here, the Nullable keyword indicates that the donorName parameter can be null. To handle the null case, we use the null-coalescing operator (??) to provide a default value of an empty string. This ensures that the donorName parameter is never null when stored in the session variable.

Now, let’s say that we want to redirect to a different page when the donorName parameter is null. To do this, we can add a conditional statement that checks if the donorName parameter is null:

[HttpPost]
public IActionResult Donor(string? donorName)
{
if (donorName == null)
{
return RedirectToAction("Error");
}

    HttpContext.Session.SetString("DonorName", donorName);
    return RedirectToAction("Description");

}

Here, we check if the donorName parameter is null using the == operator. If it is null, we redirect to an “Error” page using the RedirectToAction method. If it is not null, we store the donorName parameter in the session variable and redirect to the “Description” page.

In conclusion, allowing a null parameter in an ASP.NET Core MVC action method is easy using the Nullable keyword and the null-coalescing operator. Redirecting to a different page when the parameter is null can be achieved using a conditional statement and the RedirectToAction method.

Back