我想在控制器中获取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>}
Run Code Online (Sandbox Code Playgroud)
请检查下面的控制器代码以获取值
[HttpPost]
public ActionResult SaveValues(FormCollection collection)
{
string name = collection.Get("txtClientName");
string address = collection.Get("txtAddress");
return View();
}
Run Code Online (Sandbox Code Playgroud)
我得到空值
将name属性添加到输入字段,如:
<input id="txtClientName" name="txtClientName" type="text" />
Run Code Online (Sandbox Code Playgroud)
如果在视图中声明所有控件
@using (Html.BeginForm())
{
//Controls...
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET(WebPages,MVC,RAZOR)使用HTTP协议作为客户端和服务器之间交互的基础.要使HTTP将客户端值传递给服务器端,所有HTML元素都必须定义名称属性.HTML元素中的id属性仅供前端使用.(CSS,JavaScript,JQuery等).有关工作示例,请参阅以下代码行;
<input type="text" name="zzzz" id="xxxx"/>
Run Code Online (Sandbox Code Playgroud)
然后在控制器中,您可以使用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...
}
Run Code Online (Sandbox Code Playgroud)