接受查询字符串参数的列表(未知长度)到MVC操作

时间:2016-08-31 13:30:54

标签: c# asp.net-mvc

我正在构建一个页面,该页面将向其发送包含任意数量的productId_{index}productQuantity_{index}的查询字符串。

例如:

http://www.website.com/action?productId_1=65&productQuantity_1=1&productId_2=34&productQuantity_2=1

因此,此网址会将ProductId65映射到quantity 1ProductId 34quantity 1 {} 1

我无法更改将其发送到我未使用a solution like this的页面的方式。

我希望能够以某种方式将此格式的查询映射到强类型的对象列表。

这个问题主要是要求MVC这样做的方法,因为我已经有了使用Request对象的解决方案,但是能够做到这一点,MVC方式会更好。

2 个答案:

答案 0 :(得分:0)

你需要将查询字符串格式化为更简单易读的内容:p = id-quantity,然后你可以使用params,

例如:http://www.website.com/action?p=65-1&p34-4&p=32-23&p= ....

public ActionResult Products(params string[] p)
{
    foreach(var product in p)
    {
        var productId = product.Split('-')[0];
        var quantity = product.Split('-')[1];
    }
}

<强> [注意] 我不建议通过url&#34; GET&#34;发送这些参数,如果你使用&#34; POST&#34;它会更好更安全。形式方法。

答案 1 :(得分:0)

正如我所建议的那样,我最终使用custom model binder在行动中给我一个对象列表。

自定义模型粘合剂

public class ProductIdAndQuantityListModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;

        var products = new List<ProductIdAndQuantity>();

        for (int i = 0; i < 25; i++)
        {
            string productIdKey = string.Format("productid_{0}", i);
            string quantityKey = string.Format("productqty_{0}", i);

            string productIdVal = request[productIdKey];
            string quantityVal = request[quantityKey];

            if (productIdVal == null || quantityVal == null)
                break;

            int productId = Convert.ToInt32(productIdVal);
            int quantity = Convert.ToInt32(quantityVal);

            var productIdAndQuantity = products.FirstOrDefault(x => productId == x.ProductId);

            if (productIdAndQuantity != null)
            {
                productIdAndQuantity.Quantity += quantity;
            }
            else
            {
                products.Add(new ProductIdAndQuantity()
                {
                    ProductId = productId,
                    Quantity = quantity
                });
            }
        }

        return products;
    }
}

的Global.asax.cs

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(ICollection<Models.Basket.ProductIdAndQuantity>), new ProductIdAndQuantityListModelBinder());
}

动作

public ActionResult Index(ICollection<ProductIdAndQuantity> products)
{
    foreach (var product in products)
    {
        // Do stuff...
    }
}

谢谢大家的帮助!你可以看到它是一个未知但不是无限数量的参数,它可能只取决于我如何使用它我认为。