I've got hard time understanding how [Form]
attribute works.
Consider simple razor form:
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.Hidden("id", 1)
@Html.Hidden("g-recaptcha-response", "asdbasd")
<input type="submit">
}
And a controller that handles the request:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Form("id")] string id, [Form("g-recaptcha-response")] string response)
{
var explicitResponse = Request.Form["g-recaptcha-response"];
return View();
}
Now the problem I have is that response
parameter that is resolved with assistance of Form
attribute is null while the one I named explicitResponse
evaluates correctly to asdbasd.
To make sure this works at all, I've added id property which is resolved correctly using the same attribute.
I'll be diving into source code of that attribute to seek the answer, but perhaps someone has already done it.
So my question is: Why this attribute doesn't resolve the same value as I get explicitly from Request.Form
and if there's a workaround to avoid reimplementing that attribute.
This was just me not paying attention.
FormAttribute
is located in System.Web.ModelBinding
namespace and it can be used by WebForms.
The correct attribute to use here is BindAttribute
that is located in System.Web.Mvc
namespace.
Modified code looks like this and works as expected.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Prefix = "id")] string id, [Bind(Prefix = "g-recaptcha-response")] string response)
{
var explicitResponse = Request.Form["g-recaptcha-response"];
return View();
}