asp.net-mvc 如何在 asp.net mvc 回发控制器操作中访问 hiddenField 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5252899/
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 00:58:35  来源:igfitidea点击:

How to access hiddenField value in asp.net mvc postback controller action?

asp.net-mvcasp.net-mvc-2asp.net-mvc-3

提问by Pradip Bobhate

Can we access the asp:Labelvalue directly in an MVC postback controller action? I would also like to know how to access the hiddenFieldvalue in an ASP.NET MVC postback controller action.

我们可以asp:Label直接在 MVC 回发控制器操作中访问该值吗?我还想知道如何访问hiddenFieldASP.NET MVC 回发控制器操作中的值。

回答by David Fox

In ASP.NET MVC, you don't use <asp:...tags, but you could try POSTing any number of inputs within a form to a controller action where a CustomViewModelclass could bind to the data and let you manipulate it further.

在 ASP.NET MVC 中,您不使用<asp:...标记,但您可以尝试将表单中的任意数量的输入 POST 到控制器操作,其中一个CustomViewModel类可以绑定到数据并让您进一步操作它。

public class CustomViewModel
{
    public string textbox1 { get; set; }
    public int textbox2 { get; set; }
    public string hidden1 { get; set; }
}

For example, if you were using Razor syntax in MVC 3, your View could look like:

例如,如果您在 MVC 3 中使用 Razor 语法,您的视图可能如下所示:

@using (Html.BeginForm())
{
    Name:
    <input type="text" name="textbox1" />
    Age:
    <input type="text" name="textbox2" />
    <input type="hidden" name="hidden1" value="hidden text" />
    <input type="submit" value="Submit" />
}

Then in your controller action which automagically binds this data to your ViewModel class, let's say it's called Save, could look like:

然后在您的控制器操作中自动将此数据绑定到您的 ViewModel 类,假设它称为 Save,可能如下所示:

[HttpPost]
public ActionResult Save(CustomViewModel vm)
{
    string name = vm.textbox1;
    int age = vm.textbox2;
    string hiddenText = vm.hidden1;
    // do something useful with this data
    return View("ModelSaved");
}

回答by Darin Dimitrov

In ASP.NET MVC server side controls such as asp:Labelshould never be used because they rely on ViewState and PostBack which are notions that no longer exist in ASP.NET MVC. So you could use HTML helpers to generate input fields. For example:

在 ASP.NET MVC 服务器端控件中,asp:Label不应使用诸如此类的控件,因为它们依赖于 ViewState 和 PostBack,这些概念在 ASP.NET MVC 中不再存在。因此,您可以使用 HTML 助手来生成输入字段。例如:

<% using (Html.BeginForm()) { %>
    <%= Html.LabelFor(x => x.Foo)
    <%= Html.HiddenFor(x => x.Foo)
    <input type="submit" value="OK" />
<% } %>

and have a controller action which would receive the post:

并有一个控制器动作来接收帖子:

[HttpPost]
public ActionResult Index(SomeViewModel model)
{
    // model.Foo will contain the hidden field value here
    ...
}