在控制器中,如何从http帖子获取数据?

时间:2012-07-18 21:54:51

标签: c# asp.net-mvc model-view-controller http-post

  

可能重复:
  How to obtain data from a form using method=“post”? How to request it data in my controller?

我想简单地从表单中获取数据..下面是我的表单..在我的控制器中,如何从表单中访问数据?

<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>

控制器控制器控制器控制器

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

2 个答案:

答案 0 :(得分:4)

只需确保操作的参数与输入字段具有相同的名称,数据绑定将为您完成剩下的工作。

[HttpPost]
public ActionResult YourAction(string inputfieldName1, int inputFieldName2 ...)
{
    // You can now access the form data through the parameters

    return RedirectToAction("SearchPerson", "Person");
}

如果您的模型的属性与输入字段的名称相同,您甚至可以这样做:

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

请注意,该属性应为[HttpPost]而不是[HTTP POST]

当然也可以通过Request.Form阅读数据:

var inputData = Request.Form["inputFieldName"];

答案 1 :(得分:3)

你可以做到

[HttpPost]
public ActionResult YourAction (FormCollection form)
{
    var inputOne = form["FirstName"];

    return RedirectToAction("SearchPerson", "Person");
}