Joe
Joe

Reputation: 4183

How to pass a optional parameter into ActionResult

This works:

public ActionResult Edit(int id, CompPhone cmpPhn)
{
  var vM = new MyViewModel();
  if (cmpPhn != null) { vM.CmpPhnF = cmpPhn; }
  ...
}

If I make cmpPhn optional:

public ActionResult Edit(int id, CompPhone? cmpPhn)

I get "Error 1 The type 'MyProject.Models.CompPhone' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'.

How can I make this input parameter to the method optional?

Here's the view model

public class MyViewModel : IValidatableObject
{
...
public CompPhone CmpPhnF { get; set; }    
...
}

Calling method

[HttpPost, ValidateAntiForgeryToken]
public ActionResult PhoneTest(MyViewModel vM)
{
  if (ModelState.IsValid)
  { var cmpPhn = vM.CmpPhnF;
  return RedirectToAction("Edit", new { id = vM.AcntId, cmpPhn });
  }
  ...
}

Upvotes: 9

Views: 19223

Answers (2)

rblinzler
rblinzler

Reputation: 21

I agree with Habib, you are making the parameter nullable.

To make the parameter optional define two identical methods, one with the parameter and one without. The one without will have to use a predefined default value for it.

public ActionResult Edit(int id)
{
  var vM = new MyViewModel();
  vM.CmpPhnF = defaultValue;
  ...
}

and

public ActionResult Edit(int id, CompPhone cmpPhn)
{
  var vM = new MyViewModel();
  if (cmpPhn != null) { vM.CmpPhnF = cmpPhn; }
  ...
}

Upvotes: 1

Habib
Habib

Reputation: 223257

You are not making it optional, you are making it nullable. To make it optional you need to define a default value for the parameter. (Its only available for C# 4.0 or above):

public ActionResult Edit(int id, CompPhone cmpPhn = null)

your current code is specifying to be Nullable and it seems that CompPhone is a class not a value type, and can't be Nullable.

CompPhone? cmpPhn is equivalent to Nullable<CompPhone> where CompPhone should be a struct

Upvotes: 14

Related Questions