【问题标题】:ASP.NET MVC 3 Razor: Passing Data from View to ControllerASP.NET MVC 3 Razor:将数据从视图传递到控制器
【发布时间】:2012-06-08 22:26:22
【问题描述】:

我对 .NET 的所有事物都是全新的。我有一个带有 HTML 表单的非常基本的网页。我希望“onsubmit”将表单数据从视图发送到控制器。我看过与此类似的帖子,但没有一个答案涉及新的 Razor 语法。我如何处理“onsubmit”,以及如何从 Controller 访问数据?谢谢!!

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 razor


    【解决方案1】:

    您可以将您想要传递的视图控件包装在 Html.Beginform 中。

    例如:

    @using (Html.BeginForm("ActionMethodName","ControllerName"))
    {
     ... your input, labels, textboxes and other html controls go here
    
     <input class="button" id="submit" type="submit" value="Submit" />
    
    }
    

    当按下提交按钮时,Beginform 中的所有内容都将提交给“ControllerName”控制器的“ActionMethodName”方法。

    在控制器端,您可以像这样访问从视图中接收到的所有数据:

    public ActionResult ActionMethodName(FormCollection collection)
    {
     string userName = collection.Get("username-input");
    
    }
    

    上面的集合对象将包含我们从表单提交的所有输入条目。您可以按名称访问它们,就像访问任何数组一样: 集合[“废话”] 或 collection.Get("blah")

    您也可以直接将参数传递给您的控制器,而无需使用 FormCollection 发送整个页面:

    @using (Html.BeginForm("ActionMethodName","ControllerName",new {id = param1, name = param2}))
    {
     ... your input, labels, textboxes and other html controls go here
    
     <input class="button" id="submit" type="submit" value="Submit" />
    
    }
    
    public ActionResult ActionMethodName(string id,string name)
    {
     string myId = id;
     string myName = name;
    
    }
    

    或者您可以将这两种方法结合起来,并将特定参数与 Formcollection 一起传递。这取决于你。

    希望对你有帮助。

    编辑:当我在写其他用户时,其他用户也向您推荐了一些有用的链接。看看吧。

    【讨论】:

    • 对于组合你也可以这样做:HttpContext.Request.Form["index"];这样你就不必在参数中添加FormCollection了。
    【解决方案2】:

    按以下方式定义表单:

    @using (Html.BeginForm("ControllerMethod", "ControllerName", FormMethod.Post))

    将调用控制器“ControllerName”中的方法“ControllerMethod”。 在该方法中,您可以接受模型或其他数据类型作为输入。有关使用表单和 razor mvc 的示例,请参阅 this 教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多