Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot call method because parameter is passed by reference exception on updating mvc

Recently I have updated MVC to 5.1. I am getting exception

Cannot call action method 'Void MyAd(Inspinia_MVC5_SeedProject.Models.Ad ByRef, System.String, System.String, System.String)' on controller 'Inspinia_MVC5_SeedProject.CodeTemplates.ElectronicsController' because the parameter 'Inspinia_MVC5_SeedProject.Models.Ad& ad' is passed by reference.

on routes.MapMvcAttributeRoutes();

MyAd function is:

public void MyAd(ref Ad ad,string SaveOrUpdate,string cateogry = null,string subcategory = null)
        {
            var type = System.Web.HttpContext.Current.Request["type"];
            var isbiding = System.Web.HttpContext.Current.Request["bidingAllowed"];
            var condition = System.Web.HttpContext.Current.Request["condition"];
            var pp = System.Web.HttpContext.Current.Request["price"];
            //other huge stuff.
        }

I am using this function in different controllers.

I call the function to save data in ad object

MyAd(ref ad,"Save","Electronics","HomeAppliances");

and then I use data as ad.type.

How can I tackle this exception?

like image 704
Ayesha Avatar asked Jan 07 '23 09:01

Ayesha


2 Answers

(responding to an older post, but perhaps this will help someone)

Passing by reference works if the scope of the method being called is not "public".

I was able to pass a model by reference from an Action method to a "build model" method in one controller, but not in another. A comparison revealed that the only difference was the scope of the methods.

After changing the scope from 'public' to 'private' ('protected' works too), the issue was corrected.

like image 97
musicsecrets Avatar answered Jan 22 '23 13:01

musicsecrets


Seems pretty straight-forward to me. It tells you right out that it cannot call this action method because it requires a pass by reference. While action methods look like standard class methods, there's specific conventions and restrictions to them that are specific to actions. One of those is not being able to pass by reference, which is due to the way routing and model binding works in MVC.

Long and short, you need to change your action method signature to not pass by reference, and compensate accordingly in your action code.

like image 33
Chris Pratt Avatar answered Jan 22 '23 12:01

Chris Pratt