【问题标题】:MVC Passing Attribute as ArgumentMVC 传递属性作为参数
【发布时间】:2017-11-19 17:03:15
【问题描述】:

我正在尝试创建一个购物车,但是当尝试将 Id 作为参数传递时,会发生这种情况

http://localhost:15359/RealCartController/Order/FinalProject.Models.Clothes

HTTP 错误 404.0 - 未找到 您要查找的资源已被删除、名称已更改或暂时不可用。

这是在 RealCartController 中

   public ActionResult Order(int id)
            {
                if(Session["cart"] == null)
                {
                    List<Item> cloth = new List<Item>();
                    cloth.Add(new Item(de.Clothes.Find(id),1));
                    Session["cart"] = cloth;
                }
                else
                {
                    List<Item> cart = (List<Item>)Session["cart"];
                    int index = isExisting(id);
                    if (index == -1)
                        cart.Add(new Item(de.Clothes.Find(id), 1));
                    else
                        cart[index].Amount++;

                    Session["cart"] = cart;
                }
                return View();
            }

这是在调用函数的视图中

@if (Model != null)
{

    foreach (Clothes Id in Model)
    {
        if (Id.Amount > 0)
        {

        <div id="container">
            <div id="row">

                <img src="~/Content/img/@Html.DisplayFor(model => Id.ImagePath)" style="height:200px;width:200px;" />
                <br />
                <br />
                    @Html.ActionLink("Add To Cart", "Order", "RealCartController", new { id = Id }, null);
            </div>
        </div>
        }

    }
}

这是函数的视图

@foreach (Item item in (List<Item>)Session["cart"])
        {

            <tr>
                <td>@item.Cl.Id</td>
                <td>@item.Cl.Price</td>
                <td>@item.Cl.Amount</td>
                <td>@item.Cl.Price * item.Cl.Amount</td>
            </tr>
        }

【问题讨论】:

  • 我确认提供的链接给出了 404 错误 :=)
  • 链接指向localhost,它位于本地机器上。如果我们没有配置设置或在我们的机器中正确放置文件,我们就无法测试它的有效性。 :-\
  • @LaurentLequenne 和 Sometowngeek 它自动将其格式化为链接,并且 url 中的信息是相关的。

标签: c# asp.net-mvc parameters http-status-code-404


【解决方案1】:

它应该看起来像这样

    @Html.ActionLink("Add To Cart", "Order", "RealCartController", new { id = 
    Id.ProductId }, null);

ProductId 来自您的类/模型,是您的项目的主键

【讨论】:

    【解决方案2】:

    foreach (Clothes Id in Model) 这一行中的变量Id 是一个对象,而不是一个数字。当您尝试使用 ActionLink 函数将对象作为参数发送时,它只会发送对象类名。因此api调用解析参数失败。

    你可以看到在url中发送了一个类名。

    http://localhost:15359/RealCartController/Order/FinalProject.Models.Clothes

    FinalProject.Models.Clothes 部分应该是订单 ID 号。

    http://localhost:15359/RealCartController/Order/1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      相关资源
      最近更新 更多