在 Controller 中重用 ActionResult 代码

发布于 2025-01-07 02:13:40 字数 1893 浏览 0 评论 0原文

如果我有以下代码(编辑:抱歉,如果我不清楚,我想封装以下内容(忘记其调用的视图),以便我可以在 ActionResult)

public ActionResult ModelBased(string[] items, PostedItems postedItems) {
        var model = new ItemsViewModel();
        var selectedItems = new List<Item>();
        var postedItemIDs = new string[0];
        if (postedItems == null) postedItems = new PostedItems();

        if (items!= null && items.Any()) {
            postedCityIDs = items;
            postedItems.ItemIDs = items;
        }

        if (postedItems.ItemIDs != null && postedItems.ItemIDs.Any()) {
            postedItemIDs = postedIems.ItemIDs;
            model.WasPosted = true;
        }

        if (postedItemIDs.Any())
            selectedItems = ItemRepository.GetAll()
                .Where(x => postedItemIDs.Any(s => x.Id.ToString().Equals(s))).ToList();

        model.AvailableItems = ItemRepository.GetAll();
        model.SelectedItems = selectedItems;
        model.PostedItems = postedItems;

        return View(model);
    }

我如何在控制器的不同操作中重用它,而无需复制/粘贴。我尝试使用代码执行私有方法。但我陷入困境:

  1. 要么在操作方法中调用错误:private void Item (Item item) {//从上面复制代码},然后调用 Item(item); 在动作中;或

  2. 这与我做错的(string[] items, PostedItems postsedItems)有关;或

  3. 完全不同的事情,我没有做正确的事情。

任何例子将不胜感激。

编辑:上面的代码适用于 CheckBoxList。这是一个特定的 CheckBoxList。但我希望能够在其他视图中使用它,而不必将代码复制/粘贴到其他 ActionResults。仅调用 ActionResult 是行不通的,因为我打算做其他事情。特别是,我在每个 ActionResult 中都有向导代码,例如:

if ((nextButton != null) && ModelState.IsValid)
     return RedirectToAction("EMailConfirm");
return View("EMail/BasicDetails", myData);

返回特定视图,因此仅调用 ActionResult 将不起作用,除非我丢失了某物。

If I have the following code (EDIT: Sorry if I wasn't clear, I want to encapsulate the following (forget about the view its calling), so that I could do other stuff within the ActionResult):

public ActionResult ModelBased(string[] items, PostedItems postedItems) {
        var model = new ItemsViewModel();
        var selectedItems = new List<Item>();
        var postedItemIDs = new string[0];
        if (postedItems == null) postedItems = new PostedItems();

        if (items!= null && items.Any()) {
            postedCityIDs = items;
            postedItems.ItemIDs = items;
        }

        if (postedItems.ItemIDs != null && postedItems.ItemIDs.Any()) {
            postedItemIDs = postedIems.ItemIDs;
            model.WasPosted = true;
        }

        if (postedItemIDs.Any())
            selectedItems = ItemRepository.GetAll()
                .Where(x => postedItemIDs.Any(s => x.Id.ToString().Equals(s))).ToList();

        model.AvailableItems = ItemRepository.GetAll();
        model.SelectedItems = selectedItems;
        model.PostedItems = postedItems;

        return View(model);
    }

How might I reuse it in different Actions in my controller without having to copy/paste. I tried doing a private method with the code. But I am stuck on:

  1. Either calling it wrong within an action method : private void Item (Item item) {//copied code from above} then calling Item(item); in the action; or

  2. It has something to do with the (string[] items, PostedItems postedItems) that I am doing wrong; or

  3. Something entirely different that I am not doing right.

Any examples would be much appreciated.

EDIT: The code above works with a CheckBoxList. It's one particular CheckBoxList. But I want to be able to use it in other views without having to copy/paste the code to other ActionResults. Just calling the ActionResult won't work, because I plan on doing other things. In particular, I have code for wizards in each ActionResult, such as:

if ((nextButton != null) && ModelState.IsValid)
     return RedirectToAction("EMailConfirm");
return View("EMail/BasicDetails", myData);

which are returning specific views, so call to just the ActionResult won't work, unless I am missing something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

廻憶裏菂餘溫 2025-01-14 02:13:40

return View(model); 尝试查找原始操作的视图。

指定 return View("ModelBased", model); 以始终呈现名为 "ModelBased" 的视图


public void SomeAction(string[] items, PostedItems postedItems)
{
    // Modify the data as your like
    return ModelBased(string[] items, PostedItems postedItems);
}

public void SomeOtherAction(string[] items, PostedItems postedItems)
{
    // Modify the data as your like
    return ModelBased(string[] items, PostedItems postedItems);
}

private ActionResult ModelBased(string[] items, PostedItems postedItems) {
    var model = new ItemsViewModel();
    var selectedItems = new List<Item>();
    var postedItemIDs = new string[0];
    if (postedItems == null) postedItems = new PostedItems();

    if (items!= null && items.Any()) {
        postedCityIDs = items;
        postedItems.ItemIDs = items;
    }

    if (postedItems.ItemIDs != null && postedItems.ItemIDs.Any()) {
        postedItemIDs = postedIems.ItemIDs;
        model.WasPosted = true;
    }

    if (postedItemIDs.Any())
        selectedItems = ItemRepository.GetAll()
            .Where(x => postedItemIDs.Any(s => x.Id.ToString().Equals(s))).ToList();

    model.AvailableItems = ItemRepository.GetAll();
    model.SelectedItems = selectedItems;
    model.PostedItems = postedItems;

    return View(model);
}

return View(model); tries to find a view for the original action.

Specify return View("ModelBased", model); to always render the view named "ModelBased"


public void SomeAction(string[] items, PostedItems postedItems)
{
    // Modify the data as your like
    return ModelBased(string[] items, PostedItems postedItems);
}

public void SomeOtherAction(string[] items, PostedItems postedItems)
{
    // Modify the data as your like
    return ModelBased(string[] items, PostedItems postedItems);
}

private ActionResult ModelBased(string[] items, PostedItems postedItems) {
    var model = new ItemsViewModel();
    var selectedItems = new List<Item>();
    var postedItemIDs = new string[0];
    if (postedItems == null) postedItems = new PostedItems();

    if (items!= null && items.Any()) {
        postedCityIDs = items;
        postedItems.ItemIDs = items;
    }

    if (postedItems.ItemIDs != null && postedItems.ItemIDs.Any()) {
        postedItemIDs = postedIems.ItemIDs;
        model.WasPosted = true;
    }

    if (postedItemIDs.Any())
        selectedItems = ItemRepository.GetAll()
            .Where(x => postedItemIDs.Any(s => x.Id.ToString().Equals(s))).ToList();

    model.AvailableItems = ItemRepository.GetAll();
    model.SelectedItems = selectedItems;
    model.PostedItems = postedItems;

    return View(model);
}
不醒的梦 2025-01-14 02:13:40

您的示例不清楚,但是,我通常会将常见功能移至单独的方法中,并用 [NonAction] 属性标记它。例如

[NonAction]
protected UserInfo GetUserInfo(string username)
{
   // Return relevant data
}

,我会在您的操作方法中调用 GetUserInfo。

编辑:

您需要查看部分视图。您可以将部分视图视为可以在多个页面上重复使用的控件。例如,我可以将登录控件放在部分视图中,并将其放在多个页面上。这将促进代码的可重用性。

我无法给你这个例子,因为我有一段时间没有这样做了,但你必须执行以下操作:

  1. 而不是 return View(); 你必须 return PartialView("_NameOfYourPartialView", viewModel);
  2. 修改您的视图,使其不再是视图,而是部分视图。

您需要阅读一些内容并亲自尝试一下。

祝你好运

Your example is unclear, however, I would normally move common functionality into a seperate method and mark it with [NonAction] attribute. E.g.

[NonAction]
protected UserInfo GetUserInfo(string username)
{
   // Return relevant data
}

I would then call GetUserInfo in your action method.

Edit:

You need to look into partial views. You can think of a partial view as a control that you can re-use on multiple pages. For example, I can put a login control in a partial view and renged it on multiple pages. This will promote code re-usability.

I can't give you the example as I haven't done this for a while, but you'd have to do the following:

  1. Instead of return View(); you'll have to return PartialView("_NameOfYourPartialView", viewModel);
  2. Modify your view, so it's no longer a view, but a partial view.

You'll need to do a bit of reading and try it out for yourself.

Good luck

紧拥背影 2025-01-14 02:13:40

您可以从返回 ActionResult 的另一个操作调用此操作。

public ActionResult OtherAction()
{
    return ModelBased(items, postedItems);
}

另外,为什么要private void?您实际上想重复使用哪一部分?如果它需要一个 Item 并返回 ItemsViewModel,它应该是 private ItemsViewModel - 取决于您想要重用的部分。 void 不返回任何内容。

You can call this action from another action that returns ActionResult.

public ActionResult OtherAction()
{
    return ModelBased(items, postedItems);
}

Also, why private void? Which part do you actually want to reuse? If it takes an Item and returns ItemsViewModel, it should be private ItemsViewModel - depends on the part you want to reuse. void doesn't return anything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文