这是呈现的 html: Kayak A boat-6ren">
gpt4 book ai didi

c# - ASP.NET MVC Html.BeginForm 问题

转载 作者:太空狗 更新时间:2023-10-29 17:41:11 25 4
gpt4 key购买 nike

我有部分观点:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DomainModel.Entities.Product>" %>

<div class="item">
<h3><%= Model.Name %></h3>
<%= Model.Description %>

<% using (Html.BeginForm("AddToCart", "Cart")) { %>
<%= Html.Hidden("ProductID") %>
<%= Html.Hidden("returnUrl", ViewContext.HttpContext.Request.Url.PathAndQuery) %>
<input type="submit" value="+ Add to cart" />
<% } %>

<h4><%= Model.Price.ToString("c")%></h4>
</div>

这是呈现的 html:

<div class="item"> 
<h3>Kayak</h3>
A boat for one person
<form action="" method="post">
<input id="ProductID" name="ProductID" type="hidden" value="1" />
<input id="returnUrl" name="returnUrl" type="hidden" value="/" />
<input type="submit" value="+ Add to cart" />
</form>
<h4>$275.00</h4>
</div>

单击提交按钮时没有任何反应,我很确定这是因为表单操作属性没有值。 BeginForm(action, controller) 不应该负责渲染表单操作吗?我做错了什么?

编辑

来自 CartController AddToCart 操作的代码:

    public RedirectToRouteResult AddToCart(Cart cart, int productID, string returnUrl)
{
Product product = productsRepository.Products.FirstOrDefault(p => p.ProductID == productID);

cart.AddItem(product, 1);
return RedirectToAction("Index", new { returnUrl });
}

编辑2

呈现部分的 View :

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% foreach (var product in Model) { %>
<% Html.RenderPartial("ProductSummary", product); %>
<% } %>

<div class="pager">
Page:
<%=Html.PageLinks((int)ViewData["CurrentPage"],
(int)ViewData["TotalPages"],
x => Url.Action("List", new { page = x, category = ViewData["CurrentCategory"] })) %>
</div>
</asp:Content>

编辑 3

路线:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
null, // don't need a name
"", // matches the root URL, i.e. ~/
new { controller = "Products", action = "List", category = (string)null, page = 1 } //Defaults
);

routes.MapRoute(
null, // don't need name
"Page{page}", // URL pattern, e.g. ~/Page683
new { controller = "Products", action = "List", category = (string)null }, // defaults
new { page = @"\d+" } // constraints: page must be numerical
);

routes.MapRoute(null,
"{category}",
new { controller = "Products", action = "List", page = 1 });

routes.MapRoute(null,
"{category}/Page{page}",
new { controller = "Products", action = "List" },
new { page = @"\d+" } // constraints: page must be numerical
);

}

最佳答案

您似乎没有设置默认路由。 BeginForm 使用 UrlHelper.GenerateUrl 将操作/ Controller 名称与您的路由集合相匹配。因此,如果您没有映射到 AddToCart 的路由,则它无法为其生成 URL。尝试将此添加到路线的底部:

routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Products", action = "List", id = "" }
);

关于c# - ASP.NET MVC Html.BeginForm 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1003040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com