2010-09-21 53 views
2
// 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(); 
}); 

在表单提交之前,我需要添加一些额外的参数(路由值),这些参数只能在提交时计算。使用Html.BeginForm和jQuery添加动态参数提交

我该怎么做?

回答

5

你可以在提交前一个隐藏字段添加到窗体:

$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(); 
}); 
+1

我同意你的答案,但由于这是一个背后的脚本(推测可能与模型绑定),我将建议隐藏的输入字段应该已经被删除(即不是即时生成的) - 它应该只是改变其值。 – 2010-09-21 14:08:41

+0

@Kirk,是的,这是一个好主意。输入可能已经在服务器端生成,只能在客户端上设置它的值,除非这些隐藏字段的数量是动态的并由用户添加。 – 2010-09-21 14:11:30

+0

我无法真正拥有静态隐藏字段,因为我在页面上有无限数量的表单,并且每个提交都需要这些额外的信息,因为它是用于错误恢复的。我可以在母版页中有一个隐藏字段,但是再次出现这个问题,我不知道如何让这个值与表单一起提交。 – fearofawhackplanet 2010-09-21 14:27:05