【问题标题】:Adding dynamic parameters with Html.BeginForm and jQuery submit使用 Html.BeginForm 和 jQuery 提交添加动态参数
【发布时间】:2023-04-06 16:12:01
【问题描述】:
// html
<% using (Html.BeginForm("MyAction", "MyController", 
                   new { id = ViewContext.RouteData.Values["id"] },
                   FormMethod.Post, 
                   new { enctype = "multipart/form-data", class="myForm" }))
 { %>
    <input type="file" name="blah" />
 <% } %>



// script
$container.find('.myButton').click(function() {
    $container.find('.myForm').submit();
});

在提交表单之前,我需要添加一些额外的参数(路由值),这些参数只能在提交时计算。

我该怎么做?

【问题讨论】:

    标签: jquery asp.net-mvc form-submit routevalues html.beginform


    【解决方案1】:

    您可以在提交之前将隐藏字段附加到表单:

    $container.find('.myButton').click(function() {
        var form = $container.find('.myForm');
        form.append(
            $(document.createElement('input'))
                .attr('type', 'hidden')
                .attr('name', 'somename')
                .attr('type', 'somecalculatedvalue')
        );
        form.submit();
    });
    

    【讨论】:

    • 我同意你的回答,但由于这是一个回发场景(可能是模型绑定),我建议隐藏的输入字段应该已经被删除(即不是动态生成的) ) -- 它应该只是改变它的值。
    • @Kirk,是的,这是个好主意。输入可能已经在服务器端生成,并且只在客户端设置它的值,除非这些隐藏字段的数量是动态的并且由用户添加。
    • 我不能真正拥有静态隐藏字段,因为我在页面上有无限数量的表单,并且每次提交都需要这些额外信息,因为它用于错误恢复。我可以在母版页中有一个隐藏字段,但问题是我不知道如何让这个值与表单一起提交。
    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 2018-04-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多