问题
Possible Duplicate:
How to obtain data from a form using method=“post”? How to request it data in my controller?
I want to simply obtain data from a form.. Below is my form.. In my controller , how do i access the data from the form?
<script type="text/javascript">
$(document).ready(function () {
$("#SavePersonButton").click(function () {
$("#addPerson").submit();
});
});
</script>
<h2>Add Person</h2>
<form id="addPerson" method="post" action="<%: Url.Action("SavePerson","Prod") %>">
<table>
<tr>
<td colspan="3" class="tableHeader">New Person</td>
</tr>
<tr>
<td colspan="2" class="label">First Name:</td>
<td class="content">
<input type="text" maxlength="20" name="FirstName" id="FirstName" />
</td>
</tr>
<tr>
<td colspan="2" class="label">Last Name:</td>
<td class="content">
<input type="text" maxlength="20" name="LastName" id="LastName" />
</td>
</tr>
<tr>
<td colspan="3" class="tableFooter">
<br />
<a id ="SavePersonButton" href="#" class="regularButton">Add</a>
<a href="javascript:history.back()" class="regularButton">Cancel</a>
</td>
</tr>
</table>
</form>
Contoller Controller Controller Controller Controller
[HTTP POST]
public Action Result(Could i pass in the name through here or..)
{
Can obtain the data from the html over here using Request.Form. Pleas help
return RedirectToAction("SearchPerson", "Person");
}
回答1:
Just make sure the parameters of the action has the same name as the input fields and the data-binding will take care of the rest for you.
[HttpPost]
public ActionResult YourAction(string inputfieldName1, int inputFieldName2 ...)
{
// You can now access the form data through the parameters
return RedirectToAction("SearchPerson", "Person");
}
If you have a model whose properties have the same name as your input fields your could even do this:
[HttpPost]
public ActionResult YourAction(YourOwnModel model)
{
// You will now get a model of type YourOwnModel,
// with properties based on the form data
return RedirectToAction("SearchPerson", "Person");
}
Notice that the attribute should be [HttpPost]
not [HTTP POST]
.
It is of course possible to read the data through Request.Form
as well:
var inputData = Request.Form["inputFieldName"];
回答2:
You could do
[HttpPost]
public ActionResult YourAction (FormCollection form)
{
var inputOne = form["FirstName"];
return RedirectToAction("SearchPerson", "Person");
}
来源:https://stackoverflow.com/questions/11550947/in-the-contoller-how-do-i-obtain-data-from-an-http-post