如何将选定的dropdownbox值从mvc视图传递给控制器​​操作方法?

时间:2016-04-06 18:49:22

标签: c# ajax asp.net-mvc

我的视图中有一个下拉框,由sql数据库表填充。在下拉列表中我有不同的值,我想将按钮单击下拉列表的选定值传递给控制器​​操作方法。这是填充下拉的方式。

public ViewResult ProductDetails(int productId)
        {
            Product product = repository.Products
               .Include(p => p.Reviews)
                .FirstOrDefault(p => p.ProductID == productId);
            List<string> available = new List<string>();
            available.AddRange(product.AvailableSizes.Split(',').ToList());
            ViewData["AV"] = new SelectList(available);
            return View(product);
        }

然后在视图中:

@Html.DropDownList("AV")

我的控制器操作方法是:

public ActionResult AddToCart(Cart cart, int productId, string returnUrl, string size)
        {
            Product product = repository.Products
                        .FirstOrDefault(p => p.ProductID == productId);
            if (product != null)
            {
                cart.AddItem(product, 1,size); //no overload for method 'AddItem' takes 3 argument, Error!
            }
            return RedirectToAction("Index", new { returnUrl });
        }

最后购物车类如下:

public void AddItem (Product product, int quantity)
        {
            CartLine line = lineCollection
                .Where(p => p.Product.ProductID == product.ProductID)
                .FirstOrDefault();
            if (line == null)
            {
                lineCollection.Add(new CartLine { Product = product, Quantity = quantity  });
            }
            else
            {
                line.Quantity += quantity;
            }
        }

我试过Error with the ajax and transaction in mvc但没有运气,不知道吗?

编辑Sir Rion Williams: 整个购物车类别如下所示。

public class Cart
    {
        private List<CartLine> lineCollection = new List<CartLine>();
        public void AddItem (Product product, int quantity)
        {
            CartLine line = lineCollection
                .Where(p => p.Product.ProductID == product.ProductID)
                .FirstOrDefault();
            if (line == null)
            {
                lineCollection.Add(new CartLine { Product = product, Quantity = quantity  });
            }
            else
            {
                line.Quantity += quantity;
            }
        }
        public void RemoveLine (Product product)
        {
            lineCollection.RemoveAll(l => l.Product.ProductID == product.ProductID);
        }
        public decimal ComputeTotalValue()
        {
            return lineCollection.Sum(e => e.Product.ProductPrice * e.Quantity);
        }
        public void Clear()
        {
            lineCollection.Clear();
        }
        public IEnumerable<CartLine> Lines
        {
            get { return lineCollection; }
        }
        public class CartLine
        {
            public Product Product { get; set; }
            public int Quantity { get; set; }
        }
    }

1 个答案:

答案 0 :(得分:0)

如果您的视图包含以下元素:

@Html.DropDownList("AV")

这意味着,无论您将此发布到服务器,都需要期望一个名为AV的显式参数或一个绑定到名为AV的模型上的属性:

public ActionResult AddToCart(Cart cart, int productId, string returnUrl, string size, string AV)
{
     // AV should be populated as long as you are properly serializing
     // the <form> with the "AV" element in it and it should store the
     // selected value
}

如果您的cart对象具有已命名为AV的属性,则可以忽略此方法,因为MVC将自动绑定它。

非AJAX示例

例如,如果您想提交此值,则可以创建一个<form>元素,该元素指向您的AddToCart()操作并包含您的DropDown:

<form action='@Url.Action("AddToCart","YourController")' method='post'>
      @Html.DropDownList("AV")
      <input type='submit' value='Add to Cart' />
</form> 

当您点击提交按钮时,这会POST <form>AddToCart()操作的值,并且会将AV属性绑定到其选定的值:

// The [HttpPost] decorator allows this to accept POST requests
[HttpPost]
public void AddToCart(string AV)
{
    // You should be able to see your selected value here (example)
    var selected = AV;  
}

AJAX示例

AJAX示例与前一种方法非常相似,但实际发布<form>本身的方式不同。如果你正在使用jQuery,你可以连接一个事件来捕获submit事件,忽略它并通过AJAX手动POST内容:

<form action='@Url.Action("AddToCart","YourController")' method='post'>
      @Html.DropDownList("AV")
      <input type='submit' value='Add to Cart' />
</form> 
<script>
      $(function(){
           $('form').submit(function(e){
                // Ignore any default behavior / submission
                e.preventDefault();
                // Make an AJAX post to your action (short-hand)
                $.post('@Url.Action("AddToCart","YourController")', $(this).serialize(), function(){
                      alert('Your value was posted successfully!');
                });
           });
      });
</script>

此外,在您的AddItem()方法中,我看不到您的lineCollection变量的定义位置,应该注意的是,如果else子句被执行,那么实际上什么都不会发生:

public void AddItem (Product product, int quantity)
{
      // Create an instance of your line
      var line = lineCollection.FirstOrDefault(p => p.Product.ProductID == product.ProductID);
      if (line == null)
      {
           // Is lineCollection some global or static variable?
            lineCollection.Add(new CartLine { Product = product, Quantity = quantity  });
      }
      else
      {
           // Since line is actually created (and scoped) to this
           // method, this really isn't going to do anything
           // as line will be disposed of upon exiting this method
           line.Quantity += quantity;
      }
}