MVC ActionResult - Nullable or Optional parameter

When transferring the page number to MVC, the paged list does not require a page number. If no page number is selected, the default number is the first page.
Most of the documentation for this seems to facilitate the use of the zero coalescence operator, for example

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

Or something similar.

I am wondering if this can be used using the default options, for example.

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);
}

Although the presence in this instance of the page as a type with a zero value seems redundant.

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

Edit: Fixed null exception in third example

+4
1

Public ActionResult Demo(int? page = 1).

, . , .

, .

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
}

- public ActionResult UserDetails(int id = 123)

FYI: public ActionResult UserDetails(int id). , .

+1

Source: https://habr.com/ru/post/1659629/


All Articles