c# – ASP.NET MVC Html.BeginForm问题
发布时间:2020-12-15 04:10:30 所属栏目:百科 来源:网络整理
导读:我有部分看法: %@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControlDomainModel.Entities.Product" %div class="item" h3%= Model.Name %/h3 %= Model.Description % % using (Html.BeginForm("AddToCart","Cart")) { % %= Html.Hidden("Pr
我有部分看法:
<%@ 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> 点击提交按钮时,没有任何反应,我很确定是因为form action属性没有值.应该不要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 呈现部分的视图: <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",category = (string)null },// defaults new { page = @"d+" } // constraints: page must be numerical ); routes.MapRoute(null,"{category}",new { controller = "Products",page = 1 }); routes.MapRoute(null,"{category}/Page{page}",action = "List" },new { page = @"d+" } // constraints: page must be numerical ); } 解决方法
看起来你没有设置默认路由. BeginForm使用UrlHelper.GenerateUrl来匹配您的路由集合的操作/控制器名称.所以如果你没有映射到AddToCart的路由,那么它不能为它生成一个URL.尝试将其添加到路线的底部:
routes.MapRoute( "Default","{controller}/{action}/{id}",id = "" } ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |