MVC满足了我们对程序的client端的设计,我们必须学会服务器端与客户端之间的传值问题,才能真正的了解MVC的工作原理。
【简单实例】
Views端CSHTML代码:
<!DOCTYPE html>
<html >
<head >
<title>用户编辑</title>
</head>
<body>
@using (@Html.BeginForm("RequestForm", "Home"))
{
<div>
用户名:@Html.TextBox("UserName", null, new { @style = "width:200px" })
</div>
<div>
密码:@Html.Password("Password")
</div>
<div>
<input type="submit" value ="RequestForm" name="提交"/>
</div>
}
</body>
</html>
controller端代码:
public ActionResult Index()
{
return View(); //初始加载
}
public ActionResult RequestForm()
{
Models.UserModel user = new Models.UserModel();
user.UserName = Request.Form["UserName"]; //获取从client端传递来的值
user.pwd = Request.Form["Password"];
return View(user);
}
注意在global里面的路由映射:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // 路由名称
"{controller}/{action}/{id}", // 带有参数的 URL
new { controller = "Home", action = "user", id = UrlParameter.Optional } // 参数默认值
);
}