2012-07-26 178 views
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形式的行動,但我需要在提交之前修改隱藏的價值。是否有可能通過行動或其他方式做到這一點?

我有什麼那麼遠,

查看:

@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" /> 
} 

控制器:

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

解決方案:

似乎是不容易從控制器做到這一點,所以我最終使用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();    
     } 
    }); 

似乎運作良好...

+0

請問這種幫助ü? http://msdn.microsoft.com/en-us/library/debx8sh9.aspx – VJAI 2012-07-27 07:43:38

+0

@Mark我想我會去上面的jQuery和ajax解決方案。似乎很難從控制器中完成。 – woggles 2012-07-27 10:54:41

回答

1

這是相當困難重定向到從POST一個POST(依賴於HTTP狀態代碼沒有普遍支持),這是不可能的GET。

最簡單的解決方案可能是發佈(新)表單的結果上的一個小JavaScript。

因此,您的操作方法返回一個視圖,其中包含JavaScript中必要的數據(通過控制器的模型傳遞)。

+0

我不知道我關注 - 是否將JavaScript代碼作爲視圖模型的字符串屬性返回,以創建並提交新表單?你能舉出一個這樣的例子嗎? – woggles 2012-07-26 14:50:37

+0

@woggles:例子:不快,但DOM的'Form'接口有一個'submit'方法。我在模型上假設了一個布爾值,使視圖添加腳本,但控制器中的字符串也可以工作。 – Richard 2012-07-26 15:05:58

+0

你能檢查我上面的解決方案嗎?大概是你心中的想法? – woggles 2012-07-27 10:53:33

1

你可以嘗試這樣的事情(使用jQuery):

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