引用控制器路由时出错

时间:2018-06-21 21:40:29

标签: c# asp.net-core asp.net-core-mvc

我有一个ASP.NET核心MVC应用程序,用户可以在其中搜索要购买的物品。在此过程中,有一个搜索页面,该页面返回表中的结果列表,其中表中的每个项目都链接到详细信息页面。具有表的搜索页面的逻辑和详细信息页面的逻辑都包含在一个控制器中。在详细信息页面上,我有一个添加到购物车按钮,用户可以单击该按钮。该按钮链接到一个单独的控制器(用于购物车),而不是用于实际详细信息页面的控制器。

由于某种原因,当我输入购物车控制器操作的URL时,出现以下错误:

InvalidOperationException: Unable to resolve service for type 'Models.ResortDataJoinObj' while attempting to activate 'Controllers.ShoppingCartController'.

这里讨论的模型用于将数据存储在控制器中,该数据将被发送到视图。当在其他控制器中使用该模型时,该模型可以正常工作,因此我不确定问题出在哪里。但是由于某种原因,当我在详细信息视图中单击“添加到购物车”按钮时,服务器找不到该页面。 什么可能导致这些问题?

下面是相关代码:

starup.cs中的路由

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=resortDeals}/{action=Index}/{id?}");
                routes.MapRoute(
                  name: "shoppingcart",
                  template: "{controller=ShoppingCart}/{action=Index}/{id?}");
            });

相关的控制器动作

    public class ShoppingCartController : Controller
    {
public ShoppingCartController(ResortDataJoinObj resortDataJoinObj, ShoppingCart shoppingCart)
            {
                _shoppingCart = shoppingCart;
                _resortDataJoinObj = resortDataJoinObj;

            }
     [Route("shoppingcart")]
    public ViewResult Index()
    {
        ...
    }
    [Route("ShoppingCart/AddToShopingCart/")]
    public RedirectToActionResult AddToShopingCart(int dealId)
    {
         var selectedDeal = (from rd in _db.ResortData
                                join ra in _db.ResortAvailability on rd.RecNo equals ra.RecNoDate
                                where Convert.ToInt32(rd.RecNo) == id
                                select new ResortDealResultsObject
                                {
                                    Name = rd.Name,
                                    ImageUrl = rd.ImageUrl,
                                    ResortDetails = rd.ResortDetails,
                                    RecNo = rd.RecNo,
                                    CheckIn = ra.CheckIn,
                                    Address = rd.Address,
                                    TotalPrice = ra.TotalPrice

                                }
                                );
            ResortDataJoinObj dealJoinObj = new ResortDataJoinObj();
            List<ResortDealResultsObject> selectedDealList = new List<ResortDealResultsObject>();
            foreach (var row in selectedDeal)
            {
                //An example of only selecting certain results
                // if (row.Name == "John" && row.TotalPrice > 15)
                // {
                var tempVm = new ResortDealResultsObject
                {
                    Name = row.Name,
                    ImageUrl = row.ImageUrl,
                    ResortDetails = row.ResortDetails,
                    RecNo = row.RecNo,
                    CheckIn = row.CheckIn,
                    Address = row.Address,
                    TotalPrice = row.TotalPrice
                };
                selectedDealList.Add(tempVm);
                //}
            }
            dealJoinObj.ResDealList = selectedDealList;
            if (selectedDeal != null)
            {
                _shoppingCart.AddToCart(dealJoinObj);
            }
            return RedirectToAction("Index");
    }
}

public class resortDealsController : Controller
    {

  public IActionResult Index()
        {
        }
 public async Task<IActionResult> Details(string id)
        {
        }
   }

详细信息视图:

@model Models.ResortDealDetailObject
@{
    ViewData["Title"] = "Details";
}

<h2>Details</h2>

<div>
    @Model.Name

    @Model.Address

    @Model.ResortDetails
</div>

@Html.Partial("AddToShoppingCart", @Model)

局部视图:

 <div class="addToCart text-right">
        <p class="button ">
            @*<a class="btn btn-success" id="cartButton" asp-controller="ShoppingCart" asp-action="AddToShoppingCart" asp-route-id="@Model.RecNo">
                Add to cart
            </a>*@
            <button class="btn btn-success" onclick="search(@Model.RecNo)">
                Add to cart
            </button>
        </p>
    </div>
</form>

<script>
    function addToCart(recNo) {
        document.getElementById('cartForm').action = "/ShoppingCart/AddToShoppingCart/" + recNo;
        document.getElementById('cartForm').submit();
    }
</script>

Resort Data Join对象:

public class ResortDataJoinObj
    {
        public ResortData ResData { get; set; }
        public ResortAvailability ResAvail { get; set; }
        public string priceLowEnd { get; set; }
        public string priceHighEnd { get; set; }
        public List<ResortDealResultsObject> ResDealList { get; set; }
        public ResortDealDetailObject detailObject { get; set; }
        public ResortDealResultsObject resortDeal { get; set; }
    }

1 个答案:

答案 0 :(得分:2)

内联答案

   // could be [Route("[controller]/[action]") or it could left off all together
   [Route("[controller]")]  
   public class ShoppingCartController : Controller
   {
      public ShoppingCartController(ShoppingCart shoppingCart)
      {
         _shoppingCart = shoppingCart;
      }

      // your default route...
      public IActionResult Index()
      {
        ...
       }
    [HttpGet("{id}")] //not entirely necessary either (more of a partially forced route)
     public RedirectToActionResult AddToShoppingCart(int id)
     {
        //since routes are exact missing something like {id} would cause
        //route generator to skip any calls to this without the {id} in place.
     }
  }

这应该有效...由于您的某些内容不包含{id},因此该路由与您在路由映射中所写的不匹配,因此您将体验到当前看到的内容。

查看您从youtube视频中看到的信息,我访问了他的存储库以查看示例。实际上,他对ShoppingCart(编号startup.cs)的范围进行了调整,以使其可以通过IOC容器以任何形式(每个单独的购物车,当前已装满)使用。

还请记住,某些配置现在会有所不同,因为该存储库大约是.net core的大约2个版本,而2.1的版本则有很大的不同,例如不使用project.json来引用程序集。