Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call one Action method from another Action method(both are in the same Controller) in MVC C#?

Hi From the calling Action Method, I have:

[HttpPost]
public JsonResult SubmitForms(Note note, string action = "Submit") 
{
     //some code
     RedirectToAction("SaveDemographicForm", "PatientForms", new { model.DemographicFormData,  action="Submit" , submitAll = true });
     //some code
}

And this the Action Method that I am trying to call:

[HttpPost]
public JsonResult SaveDemographicForm(DemographicForm demographicForm, string action = "Save", bool submitAll = false )
{
      //Some code
}

What am I doing wrong here? Thanks in advance.

like image 975
user2948533 Avatar asked Aug 18 '15 12:08

user2948533


People also ask

Can we have two action methods with same name in MVC?

While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.

How do you call an action in the same controller?

you want to call same function of controller. In this case there is no need to add action before function name. this is simple you can call function of same controller using $this->functionName().

How can we call one controller method from another controller method in MVC?

I'm assuming you want to return that action's result. var ctrl= new MyController(); ctrl. ControllerContext = ControllerContext; //call action return ctrl. Action();


2 Answers

If they are both in the same controller you don't need to redirect to action, just call it directly.

[HttpPost]
public JsonResult SubmitForms(Note note, string action = "Submit") 
{
     //some code
     return SaveDemographicForm(new DemographicForm { /*your properties*/ }, "Save", false);
}

[HttpPost]
public JsonResult SaveDemographicForm(DemographicForm demographicForm, string action = "Save", bool submitAll = false )
{
      //return some json object
}
like image 117
Stephen Brickner Avatar answered Sep 21 '22 12:09

Stephen Brickner


Just call with no return

[HttpPost]
public JsonResult SubmitForms(Note note, string action = "Submit") 
{
     SaveDemographicForm(new DemographicForm { /*your properties*/ }, "Save", false);

     //somecode
     //submitforms return
}

[HttpPost]
public JsonResult SaveDemographicForm(DemographicForm demographicForm, string action = "Save", bool submitAll = false )
{
      //return some json object
}
like image 30
Nurkartiko Avatar answered Sep 22 '22 12:09

Nurkartiko