Alex Rivera | Logout

How to pass a optional parameter into ActionResult

Asked 2012-09-18T04:21:26.010
9

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 });
  }
  ...
}
Edit
Report

1 Answer

14

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

answered 2012-09-18T04:22:25.543

Your Answer