简体   繁体   English

如何从动作中提交带有隐藏字段的表单?

[英]How to submit a form with hidden fields from an action?

Say I have the following form that's in classic asp: 说我有经典asp中的以下形式:

<form name="impdata" id="impdata" method="POST" action="http://www.bob.com/dologin.asp">
<input type="hidden" value="" id="txtName" name="txtName" />
</form>

I need to simulate the action of submitting the form in asp.net mvc3, but I need to modify the hidden value before submitting. 我需要模拟在asp.net mvc3中提交表单的操作,但我需要在提交之前修改隐藏的值。 Is it possible to do this from the action or in another way? 是可以通过动作还是以其他方式做到这一点?

What I have so far... 到目前为止我有什么......

View: 视图:

@using (Html.BeginForm("Impersonate", "Index", FormMethod.Post, new { id = "impersonateForm" }))
{                       
    <input id="Impersonate" class="button" type="submit" value="Impersonate" action />
    <input type="hidden" value="" id="txtName" name="txtName" />
}

Controller: 控制器:

[HttpPost]
public ActionResult Impersonate(string txtName)
{
txtName = txtName + "this string needs to be modified and then submitted as a hidden field";  
//Redirect won't work needs the hidden field
//return Redirect("http://www.bob.com/dologin.asp");
}

Solution: 解:

Seems that it isn't easy to do this from the controller so I ended up using jQuery. 似乎从控制器执行此操作并不容易,因此我最终使用了jQuery。 The action returns a JsonResult. 该操作返回JsonResult。 Something like: 就像是:

<button id="Impersonate" class="button" onclick="Impersonate()">Impersonate!</button>

<form name="impdata" id="impersonateForm" action="http://www.bob.com/dologin.asp">
  <input type="hidden" value="" id="txtName" name="txtName" /> 
</form>

function Impersonate() {           
    $.ajax({
        type: 'POST',
        asynch: false,
        url: '@Url.Action("Impersonate", "Index")',
        data:
            {
                name: $('#txtName').val()                    
            },
        success: function (data) {                
            $('#txtName').val(data.Name);              
            $('#impersonateForm').submit();               
        }
    });

Seems to work well... 似乎运作良好......

It is rather hard to redirect to a POST from a POST (relies on HTTP status codes without universal support), and it is impossible from a GET. 从POST重定向到POST是很困难的(在没有通用支持的情况下依赖于HTTP状态代码),而且从GET开始是不可能的。

The simplest solution is probably a little JavaScript on the result that posts the (new) form. 最简单的解决方案可能是发布(新)表单的结果上的一点JavaScript。

Thus you action method returns a view with the necessary data in it (passed via the model from the controller) which will include the JavaScript. 因此,action方法返回一个视图,其中包含必要的数据(通过模型从控制器传递),其中包含JavaScript。

你可以试试这样的东西(使用jquery):

<input id="Impersonate" class="button" type="submit" value="Impersonate"    onclick="$('#txtName').val('new value')" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM