如何在MVC c#中从另一个Action方法调用一个Action方法(两者都在同一个控制器中)

本文关键字:Action 方法 一个 两者都 同一个 控制器 MVC 另一个 调用 | 更新日期: 2023-09-27 18:08:34

嗨从调用动作方法中,我有:

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

这是我要调用的动作方法:

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

我在这里做错了什么?

如何在MVC c#中从另一个Action方法调用一个Action方法(两者都在同一个控制器中)

如果它们都在同一个控制器中,你不需要重定向到action,只需要直接调用它。

[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
}

直接调用,不返回

[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
}

RedirectToAction()返回RedirectToRouteResult:

public ActionResult AnotherAction(int id)
{
    //Do something with the id ...
    return View()
}

public RedirectToRouteResult DoAndRedirect()
{            
    //Do something and go to the desired view:
    return RedirectToAction("AnotherAction", new { id = x.ID });
}
    使用System.Web.Mvc
  • ;
  • 使用System.Web.Mvc.Html;
  • public ActionResult Index()
    {
        HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
        helper.RenderAction("Index2");//call your action
        return View();
    }
    public ActionResult Index2(/*your arg*/)
    {
        //your code
        return new EmptyResult();
    }