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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Habib for clearing that subtlety between nullable and optional up. I prefer your answer over rablinz's since it doesn't require duplicating the method. And yes CompPhone is a class.
@Joe, rablinz's answer is also valid, but if you are using .Net framework 4.0 or above then it comes with C# 4.0 which has the default parameter option for a method. Prior to that version, you have to adapt to rablinz's answer
I've added the calling method to my question. You answered how to take the class into a method. I have a follow up question of how to pass a class out of a method. When I debug the calling method the id but not the cmpPhn gets added to the route values. Thanks
thanks to @Joe for asking this by using nullable and for you Habib to point out the difference, I confused the two for the same until encountered this post, lucky day for me!
1

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; } ... } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.