2011-08-11 91 views
0

我有以下的局部視圖BuyProduct.ascxHtml.DropDownList自動添加前綴

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

<span class="price">Precio: <em><strong><%: Html.Price(Model) %></strong></em></span> 

<div class="wrapper"> 
<% if (Model.Active) { %> 
    <% using (Html.BeginForm("AddToCart", "ShoppingCart", new { id = Model.ProductId }, FormMethod.Post, new { id = "addtocart-form" })) {%> 

      <% if (Model.MetricType == (int)ProductMetricType.Units) { %> 
       <%: Html.DropDownList("Quantity" , new SelectList(DropDownLists.Units , "Value", "Key" , Model.MetricType)) %> 
      <% } else { %> 
       <%: Html.DropDownList("Quantity", new SelectList(DropDownLists.Kilograms, "Value", "Key", Model.MetricType)) %> 
      <% } %> 

     <input type="submit" value="Comprar" /> 
    <% } %> 
<% } else { %> 
    <span class ="buttonBig">Sin existencias!</span> 
<% } %> 
</div> 

如果我在一個視圖中使用它的下拉列表的名稱保持不變,但如果我用它例如EditorTemplate內:

<%@ Import Namespace="MvcMusicStore"%> 
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMusicStore.Models.Product>" %> 
<li> 
    <h3><%: Html.Truncate(Model.Name, 25) %></h3> 
    <p><a href="<%: Url.Action("Details", "Store", new { id = Model.ProductId }) %>"><img alt="<%: Model.Name %>" src="<%: Model.ProductArtUrl %>" width="180" height="165" /></a></p> 
    <% Html.RenderPartial("BuyProduct", Model); %> 
</li> 

我的控制器代碼:

public ActionResult AddToCart(Guid id, int quantity = 1) { 

與MO名稱的前綴del類被添加到DropDownList名稱(Product.Quantity插入的數量)並且我的操作不再獲得正確的值,有關如何解決這兩種情況的任何想法?

回答

1

在DropDownList擴展中,SelectInternal方法包含以下構造以生成唯一名稱。

string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); 

我想這是由於您正在使用模板,包含模型名稱「Product」與成員名稱「Quantity」一起呈現。可能避免使用多個模板時發生名稱衝突。

如果你真的想「重寫」這種行爲,DropDownList擴展的自定義實現可能是你最好的選擇。