How to pass an optional parameter to ActionResult

It 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 an unimaginable value type in order to use it as the "T" parameter in the generic type or "System.Nullable" method.

How can I make this input parameter optional?

Here's a presentation model

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

Call method

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

You do not make it optional, you make it nullable . To make this optional, you need to define a default value for the parameter. (Available only for C # 4.0 or higher):

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

your current code indicates nullable , and it seems that CompPhone is a class, not a value type, and cannot be nullable .

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

+12
source

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

So that the parameter does not necessarily define two identical methods: one with the parameter and one without. Without it, you 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; } ... } 
+1
source

Source: https://habr.com/ru/post/925625/


All Articles