c# - 如何从操作中提交带有隐藏字段的表单?

标签 c# asp.net asp.net-mvc-3

假设我有以下经典 asp 形式:

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

我需要在asp.net mvc3中模拟提交表单的 Action ,但是需要在提交前修改隐藏值。是否可以通过 Action 或其他方式做到这一点?

到目前为止我有什么......

查看:

@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");
}

解决方案:

似乎从 Controller 执行此操作并不容易,所以我最终使用了 jQuery。该操作返回一个 JsonResult。 像这样的东西:

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

似乎工作得很好......

最佳答案

很难从 POST 重定向到 POST(依赖于没有普遍支持的 HTTP 状态代码),而且从 GET 重定向也是不可能的。

最简单的解决方案可能是在发布(新)表单的结果上使用一些 JavaScript。

因此,您的操作方法会返回一个 View ,其中包含必要的数据(通过模型从 Controller 传递),其中将包含 JavaScript。

关于c# - 如何从操作中提交带有隐藏字段的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11671355/

相关文章:

C# 在调用方法之前等待超时并在连续调用时重置计时器

c# - 如何在 asp.net 中创建多 View 控件并在运行时对其进行操作?

javascript - 检查 RadListView ItemTemplate 中的 RadButton 复选框 - 客户端

asp.net - 报表查看器如何与 SSRS 通信?

ASP.NET:ImageButton 不在中间

asp.net-mvc - MVC3 的奇怪名称远程验证

c# - 在 IIS Windows 7 中无法访问此站点

c# - 突出显示 DataGrid 单元格中的部分文本

asp.net-mvc-3 - DropDownListFor - 不选择 "Selected"值

asp.net-mvc - 如何将数据库值放入 asp.net mvc3 Controller 中的数组中