简体   繁体   中英

Set MVC3 parameters to default if empty or null in controller

I am struggling to default CId and SId to 1 if the parameters are empty,

  public ViewResult Index(int? CId,int?SId,string name,int? p)
    {

        if (CId == 0 || SId == 0)
        {
            CId = 1;
            SId = 1;
        }

Then I will use the values for a normal query. Thanks for any help

Cid and Sid is Nullable , so you can use HasValue property to check if the variable has value or not (null)

  public ViewResult Index(int? CId,int?SId,string name,int? p)
  {
        if (!CId.HasValue || !SId.HasValue)
        {
            CId = 1;
            SId = 1;
        }
  }

Just curious but have you tried:

public ViewResult Index(string name,int? p,int? CId = 1,int? SId = 1)
    {


    }

You have to rearrange them, because the default valued parameters have to come last. Also, being that they're nullable, I'm not actually sure if this will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM