MVC View提交数据给Controller以及Controller接收View数据的方法:
一、View必须使用元素将上传数据包括起来,并且每个上传元素必须要有name属性,否form元素不会提交数据
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>add</title>
</head>
<body>
<div>
<form method="post" action="/UserInfo/processAdd">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="用户注册" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
二、Cotroller控制器中对应的方法中接收提交的数据
1、使用FormCollection获取数据
string username = collection[“UserName”]??“”;
int age =int.Parse(collection[“Age”]);
2、使用Request获取数据
string username = Request[“UserName”] ?? “”;
int age = int.Parse(Request[“Age”]);
public ActionResult processAdd(FormCollection collection)
{
//使用FormCollection获取数据
string username = collection["UserName"]??"";
int age =int.Parse(collection["Age"]);
//使用Request获取数据
// string username = Request["UserName"] ?? "";
// int age = int.Parse(Request["Age"]);
if (username != "")
{
string sqltxt = "insert into UserInfo values(@UserName,@Age)";
int jg = SqlHelper.ExecuteNoneQuery(sqltxt, new SqlParameter[] {
new SqlParameter("@UserName",username),
new SqlParameter("@Age",age)
});
}
return RedirectToAction("Index");
}