asp.net-mvc 如何在操作方法 ASP.NET mvc 中访问我的 formcollection?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6995285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:24:08  来源:igfitidea点击:

How to access my formcollection in action method ASP.NET mvc ?

asp.net-mvc

提问by michael

I have form collection accessed in action method ,but how to get the value of it .I tried like this

我在 action 方法中访问了表单集合,但是如何获取它的值。我试过这样

string value = collection[1];

but I am not getting the value .How can I access the value in action method.

但我没有得到值。如何在操作方法中访问该值。

回答by Germando

If you have:

如果你有:

<input type="text" name="inputName" />

You could use the attribute name of the element like below:

您可以使用元素的属性名称,如下所示:

[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
     string value = Convert.ToString(collection["inputName"]);
     ...
     return View();
}    

回答by jim tollan

I think you should attempt to stear clear of the formcollection object if you are able to, in favour of a strongly typed viewmodel. there are a few examples here on SO and i've linked the 1st one that I searched for:

我认为如果可以,您应该尝试清除 formcollection 对象,以支持强类型视图模型。这里有一些关于 SO 的例子,我已经链接了我搜索的第一个例子:

passing FormCollection to controller via JQuery Post method and getting data back...

通过 JQuery Post 方法将 FormCollection 传递给控制器​​并取回数据......

however, if you're keen to tie yourself in knots :), then here's an example iterating thro a formcollection:

但是,如果您很想打结:),那么这里有一个通过 formcollection 进行迭代的示例:

http://stack247.wordpress.com/2011/03/20/iterate-through-system-web-mvc-formcollection/

http://stack247.wordpress.com/2011/03/20/iterate-through-system-web-mvc-formcollection/

回答by ipr101

Something like (code not tested) -

类似(代码未测试)-

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNewLink(FormCollection collection)
{
    string url = collection[1].ToString();
}

回答by Praveen Prasad

Create a view like this

创建这样的视图

<form action="/myController/myAction" method="post">
User Name <input type="text" name="userName" /> <br>
Country <input type="text" name="country" /><br>
<input type="submit" value="submit" />
</form>

Create action like below

创建如下动作

public ActionResult myAction(string userName, string country){
      //do some thing with userName
      //asp.net mvc3 has automatically bind that for you
}

Note: Above written code is not a recommended way of doing things, its just for a demo.

注意:以上编写的代码不是推荐的做事方式,仅用于演示。

回答by Hemlata Gehlot

Please try this example,hope it will help ...

请试试这个例子,希望它会有所帮助...

 public class UserName
    {        
       public string FName { get; set; }
       public string LName{ get; set; }               
    }


        [HttpGet]
        public ActionResult FormCollectionEg()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FormCollectionEg(FormCollection data)
        {
            UserName UserObj = new UserName();
            UserObj.FName = data["fname_name"];
            UserObj.LName = data["lname_name"];
            return  RedirectToAction("DisplayFormCollectionData", UserObj);           
        }


        public ActionResult DisplayFormCollectionData(UserName reg)
        {
             return View(reg);
        }

Create two view - DisplayFormCollectionData FormCollectionEg

创建两个视图 - DisplayFormCollectionData FormCollectionEg

DisplayFormCollectionData

显示表单集合数据

@model YourProjectNamespace.Models.UserName

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>DisplayFormCollectionData</title>
</head>
<body>
    <div>
        <h4>User Deatails</h4>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @*@Html.DisplayNameFor(model => model.FName)*@
                First Name....
            </dt>

            <dd>
                @Html.DisplayFor(model => model.FName)
            </dd>

            <dt>
                @*@Html.DisplayNameFor(model => model.LName)*@
                Last Name...
            </dt>

            <dd>

                @Html.DisplayFor(model => model.LName)
            </dd>

        </dl>
    </div>
    <p>
        @*@Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
        @Html.ActionLink("Back to List", "Index")*@
    </p>
</body>
</html>

FormCollectionEg-

FormCollectionEg-

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>FormCollectionEg</title>
</head>
<body>
    @using (Html.BeginForm("FormCollectionEg", "Home"))
    {
        <table>
            <tr>
                <td>Enter First Name</td>
                <td><input type="text" id="fname_id" name="fname_name" /></td>
            </tr>
            <tr>
                <td>Enter Last Name</td>
                <td><input type="text" id="lname_id" name="lname_name" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" /></td>
            </tr>
        </table>



    }

</body>
</html>

回答by Marty A

My preferred option is to use UpdateModel.

我的首选是使用UpdateModel

Instead of manually mapping the fields, this MVC method will automatically bind the properties from the data available in the request, the same way as if you had passed a strict type in as a parameter to the action.

此 MVC 方法将自动绑定请求中可用数据的属性,而不是手动映射字段,就像您将严格类型作为参数传递给操作一样。

[HttpPost]
public ActionResult FormCollectionEg()
{
    var model = new Username();

    UpdateModel<Username>(model);

    return View(model);
}

The above code will include data from the QueryString aswell as the form data which may not be suitable. If you were using a parameter in the action, you'd restrict this by using [FromBody], but with UpdateModel you can still achieve the same thing by passing in the FormCollection as the value provider.

上面的代码将包括来自 QueryString 的数据以及可能不合适的表单数据。如果您在操作中使用参数,您将通过使用 [FromBody] 来限制它,但使用 UpdateModel 您仍然可以通过将 FormCollection 作为值提供程序传入来实现相同的目的。

[HttpPost]
public ActionResult FormCollectionEg(FormCollection collection)
{
    var model = new Username();

    UpdateModel<Username>(model, collection);

    return View(model);
}

回答by Ishwor Khadka

See your HTML file (or use Inspect Element) to see the name attribute in the input field. For instance if you have

查看您的 HTML 文件(或使用 Inspect Element)以查看输入字段中的 name 属性。例如,如果你有

<input type = "text" name = "YourName"/>

In the controller,

在控制器中,

[HttpPost]
public ActionResult ActionName(FormCollection fc)     /*Using FormCollection*/
        {
                string variable_name = fc["YourName"];
                return View();
        }

FormCollection is one way of retrieving view data in controller. Depending on the type of value in input, you can parse its non-string value to string in the Action method.

FormCollection 是在控制器中检索视图数据的一种方式。根据输入中值的类型,您可以在 Action 方法中将其非字符串值解析为字符串。