Daniel Mackenzie Daniel Mackenzie - 1 month ago 8
C# Question

MVC ActionResult - Nullable or Optional parameter

When passing a page number to my MVC action for a paged list, it's not required to supply a page number. If no page number is selected the number defaults to the first page.

Most of the documentation for this seems to favour the use of the null coalescing operator, e.g.

Public ActionResult Demo(int? page)
{
const int pageSize = 10
var model _db.Model.ToPagedList(page ?? 1, pageSize);
return View(model);
}


Or something similar.

I'm wondering if there is a benefit of using this over using default parameters, e.g.

Public ActionResult Demo(int page = 1)
{
const int pageSize = 10
var model _db.Model.ToPagedList(page, pageSize);
return View(model);
}


Or even

Public ActionResult Demo(int? page = 1)
{
const int pageSize = 10
var model _db.Model.ToPagedList(page.Value, pageSize);
return View(model);
}


Though having page as a nullable type in this instance seems redundant.

Is there any benefit of using one of these methods in particular or is it just syntactic sugar.

Edit: Fixed null exception in third example

Win Win
Answer

The last one doesn't make sense Public ActionResult Demo(int? page = 1).

Based on your scenario, first two action methods won't make any different since the parameter is for page number. People expect to land on a first page if no parameter is supplied.

However, you do not want to use optional parameter for if you care about the value.

public ActionResult UserDetails(int? id)
{
    if (!id.HasValue)
        return View("UserNotFound"); // Or return a message.

    int userId = id.Value; 
    var user = _userService.GetUserById(userId);
    // Do something
}

You cannot use optional parameter in above scenario - public ActionResult UserDetails(int id = 123)

FYI: You do not want to use public ActionResult UserDetails(int id). It'll cause a crash if id is not supplied.

Comments