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 });
}
...
}
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With