asp.net-mvc 在控制器中获取 HTML 控件值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15738754/
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
Get HTML controls value in Controller
提问by user2218549
I want to get HTML textbox value in controller. Below is my view code
我想在控制器中获取 HTML 文本框值。下面是我的查看代码
@using (Html.BeginForm("SaveValues", "TestGrid",FormMethod.Post))
{
<table>
<tr>
<td>Customer Name</td>
<td>
<input id="txtClientName" type="text" />
</td>
<td>Address</td>
<td>
<input id="txtAddress" type="text" /></td>
<td>
<input id="btnSubmit" type="submit" value="Submit" /></td>
</tr>
</table>}
Please check my controller code below to get the values
请检查下面我的控制器代码以获取值
[HttpPost]
public ActionResult SaveValues(FormCollection collection)
{
string name = collection.Get("txtClientName");
string address = collection.Get("txtAddress");
return View();
}
I am getting null values
我得到空值
回答by Gurmeet
add name attribute to your input fields like:
将 name 属性添加到您的输入字段,例如:
<input id="txtClientName" name="txtClientName" type="text" />
回答by Cengiz Araz
If you declare all your controls in the view inside the
如果您在视图中声明所有控件
@using (Html.BeginForm())
{
//Controls...
}
ASP.NET (WebPages, MVC, RAZOR) uses HTTP protocol as base for the interactions between client and server. And to make HTTP pass client-side values to the server-side all HTML elements must have name attributes defined. The id attribute in HTML element is just for the front-end use. (CSS, JavaScript, JQuery, etc.). See the below lines of code for a working example;
ASP.NET(WebPages、MVC、RAZOR)使用 HTTP 协议作为客户端和服务器之间交互的基础。并且要使 HTTP 将客户端值传递到服务器端,所有 HTML 元素都必须定义名称属性。HTML 元素中的 id 属性仅供前端使用。(CSS、JavaScript、JQuery 等)。有关工作示例,请参阅以下代码行;
<input type="text" name="zzzz" id="xxxx"/>
Then in the controller you can access the controls with FormCollection object. It includes all controls described with a name attribute.
然后在控制器中,您可以使用 FormCollection 对象访问控件。它包括用 name 属性描述的所有控件。
//
// POST:
[HttpPost]
public ActionResult CreatePortal(FormCollection formCollection)
{
// You can access your controls' values as the line below.
string txtValue = formCollection["zzzz"];
//Here is you code...
}
回答by user3065134
To Get the HTML Control Value in the Controller through Form collection, You need to add "name" attribute to your HTML Controls.
要通过表单集合获取控制器中的 HTML 控件值,您需要向 HTML 控件添加“名称”属性。
回答by Saeed Afshari
I Asp.net MVC Html.BeginForm use name attribute of html element for serializing. Then you have to fill name attribute of html element
我 Asp.net MVC Html.BeginForm 使用 html 元素的 name 属性进行序列化。然后你必须填写 html 元素的 name 属性
回答by Dumisani
Try this:
尝试这个:
Request.Form["controlID"]

