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

前端之家收集整理的这篇文章主要介绍了c# – ASP.NET MVC Html.BeginForm问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有部分看法:
<%@ 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 = "" }
);
原文链接:https://www.f2er.com/csharp/92573.html

猜你在找的C#相关文章