ASP.NET MVC 'the same' 控制器操作中的两个为不同的目的返回不同的视图

ASP.NET MVC two of 'the same' controller actions returning different views for different purposes

我有两个控制器操作,其中一个用于以标准方式 return 视图,另一个 return 用于同一视图的一大块,例如用于 javascript 模式在我的应用程序的其他地方。我的问题是执行此操作的最佳实践方法是什么,或者我的操作方法是否合适。也许我应该将重复的代码移到辅助方法中?

(注意 Create View 里面有 _Create 部分)

现在我有:

public ActionResult Create(int someParamater)
{
    //Lots of code 
    return View(model);
}

public PartialViewResult GetCreatePartial(int someParameter)
{
    //All of the same code as in Create
     return PartialView("_Create", model);
}

您可以检查某些条件,并在此基础上 return PartialViewView,而不是创建单独的操作:

public ActionResult Create(int someParamater)
{
    if(Request.IsAjaxRequest())   // check here if ajax call return partial
       return PartialView("_Create", model);
    else
       return View(model); // otherwise return Full View
}

如果您的 GetCreatePartial 方法确实可以独立调用,并且 someParameter 参数在视图中也可用,您可以在父视图中使用 Html.Action() 调用它。

例如 (Create.cshtml):

<div>
    <span>some parent view stuff</span>
</div>

<div class="partial-wrapper">
    @Html.Action("GetCreatePartial", new { someParameter = Model.someParameter })
</div>

Html.Action