【问题标题】:In the contoller, how do i obtain data from an http post? [duplicate]在控制器中,我如何从 http 帖子中获取数据? [复制]
【发布时间】:2012-07-18 21:54:50
【问题描述】:

可能重复:
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");
}

【问题讨论】:

  • 你已经发布了两次相同的问题
  • @gilly3 几分钟前被同一个 OP 意外提出
  • @HatSoft - 当有人投票关闭一个重复的问题时,该评论会自动生成。你是说这不是一个重复的问题吗?
  • @gilly3 嗯我不知道欢呼伙伴

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


【解决方案1】:

只需确保操作的参数与输入字段具有相同的名称,数据绑定将为您处理其余的工作。

[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"];

【讨论】:

    【解决方案2】:

    你可以的

    [HttpPost]
    public ActionResult YourAction (FormCollection form)
    {
        var inputOne = form["FirstName"];
    
        return RedirectToAction("SearchPerson", "Person");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多