【问题标题】:How to pass selected value of dropdownbox from a mvc view to controller action method?如何将下拉框的选定值从 mvc 视图传递给控制器​​操作方法?
【发布时间】:2016-04-06 18:49:22
【问题描述】:

我的视图中有一个由 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,但没有运气,知道吗?

为里昂·威廉姆斯爵士编辑: 下面是整个购物车类,供您了解更多信息。

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

【问题讨论】:

    标签: c# ajax asp.net-mvc


    【解决方案1】:

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

    @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 示例

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

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

    当您单击提交按钮时,这会将您的 &lt;form&gt; 的值 POST 绑定到 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 示例的工作方式与前面的方法非常相似,但在&lt;form&gt; 本身的实际发布方式上有所不同。如果您使用 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;
          }
    }
    

    【讨论】:

    • Rion 谢谢你,但如果我对 mvc 很陌生,是否可以说得清楚一点?我没有一个名为 AV 的属性,也没有一个参数,你有什么建议?
    • 嗯,简单地“检查”您的值是否已发布,最简单的方法是您可以在添加到购物车方法中添加一行来检查AV 值,如下所示:@987654344 @。您可以使用调试器查看该值是否被正确填充,然后根据需要使用它。或者,您可以使用我之前提到的方法,将参数实际添加到名为 AV 的操作中,MVC 将自行处理绑定值。
    • 威廉姆斯爵士,您能否再看看我的问题,我在操作方法中传递的参数“大小”显示错误,错误写在问题中。再次感谢您
    • 您可以看到购物车行集合,这是一个私有方法,问题会相应更新以获取更多信息。
    • 使用建议的方法,值不会发布到控制器,一旦我通过警报(大小)单击按钮,我就会得到值,但值没有发布到控制器显示 null,有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多