【问题标题】:Getting name of button on postback获取回发按钮的名称
【发布时间】:2013-01-16 16:36:49
【问题描述】:

我通过为每种产品动态构建了一个“购买产品”页面。每个产品都有一个“添加到购物篮”按钮,通过将pID 作为按钮name 属性来区分每个产品。我现在想在回发时在我的控制器中获取name 属性的值。不知道该怎么做:

查看:

@foreach (Ecommerce.Models.HomeModels.Product product in Model)
{
    using (Html.BeginForm())
    {
        @Html.Label(product.Name);
        <br />
        @Html.Label(product.Description);
        <br />
        @Html.Label(product.UnitPrice.ToString());
        <p></p>


        <input name="@product.ID" type="submit" value="Add to Basket" /> 
    }
}

控制器:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult BuyProducts(string button)
        {

        }

【问题讨论】:

    标签: button razor asp.net-mvc-4 postback name-attribute


    【解决方案1】:

    如果您在表单中没有多个提交按钮,则无需在服务器端知道单击的提交按钮的名称是什么。还有其他方法可以将您的 ID 发送回服务器:

    为什么不在表单中生成一个隐藏字段来保存和发布数据?

    @foreach (Ecommerce.Models.HomeModels.Product product in Model)
    {
        using (Html.BeginForm())
        {
            <input type="hidden" name="productId" value="@product.ID" />
            <input  type="submit" value="Add to Basket" /> 
        }
    }
    

    然后你就可以在你的控制器中获取隐藏字段的值了:

    public ActionResult BuyProducts(string productId)
    {
        //..
    }
    

    【讨论】:

    • 有没有更好的方法来提供这个功能?而不是在一般情况下搞乱产品 ID?
    • 不,您需要 id 因为您需要以某种方式告诉服务器选择了哪个产品。因此,您需要将产品 ID 存储在 Html 中的某个位置,然后您需要将其发送到服务器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2014-10-20
    相关资源
    最近更新 更多