Domanda

Ho una visione parziale:

<%@ 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>

Ed ecco l'html che viene reso:

<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> 

Non succede nulla quando si fa clic sul pulsante di invio e sono abbastanza sicuro che l'attributo dell'azione del modulo non ha valore. BeginForm (azione, controller) non dovrebbe occuparsi di elaborare l'azione del modulo? Cosa sto sbagliando?

Modifica

Codice dall'azione AddToCart di CartController:

    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 });
    }

MODIFICA 2

La vista che rende il parziale:

<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>

EDIT 3

Percorsi:

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
        );

    }
È stato utile?

Soluzione

Sembra che tu non abbia un percorso predefinito impostato. BeginForm utilizza UrlHelper.GenerateUrl per abbinare i nomi di azione / controller alla raccolta del percorso. Quindi, se non hai un percorso mappato su AddToCart , non può generare un URL per esso. Prova ad aggiungere questo in fondo ai tuoi percorsi:

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

Altri suggerimenti

Questo è dal principale esempio di applicazione usato nell'eccellente libro "Pro ASP MVC Framework" di Steven Sanderson.

Stranamente ho fatto esattamente lo stesso errore e ho omesso la chiamata .MapRoute finale indicata nell'elenco nella pagina 130.

routes.MapRoute("Default", "controller}/{action}"

È stata la risposta di Johnny G a questo post che mi ha aiutato a trovare anche il mio errore.

Bello Johnny!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top