Say I have the following form that’s in classic 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. 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. The action returns a 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.
The simplest solution is probably a little JavaScript on the result that posts the (new) form.
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.