Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 });
  }
  ...
}
like image 610
Joe Avatar asked Sep 18 '12 04:09

Joe


People also ask

How do you pass an optional parameter?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

Can out parameter be optional C#?

also C# and . NET framework hast many many data structures that are very flexible like List and Array and you can use them as an output parameter or as return type so there is no need to implement a way to have optional output parameters.

What is optional parameter in C#?

C# Optional Arguments It means we call method without passing the arguments. The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.

Are optional parameters bad?

The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.


1 Answers

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

like image 124
Habib Avatar answered Oct 21 '22 14:10

Habib