一个URL要求, ASP.NET MVC引擎将分析URL要使用Controller, 这个Controller(取而代之的是,真实的方法Controller的Action)从数据库或者其它数据源获取数据,通常这些数据是一个业务的模型类(Model). Controller将Model对象传递给页面(View), 页面显示在浏览器上。
mvc的工作原理例如以下图:
一、建立第一个MVCProject;
如图:
二、新建一个类增加Model:
在Models文件下增加一个新的类,命名为“ Login_BS”,用来推断登录是否成功。
如图:
代码例如以下:
<span style="font-family:Microsoft YaHei;font-size:12px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyFirstMvcProject.Models
{
public class Login_BS
{
public bool login(string username,string password)
{
if(username=="1"&&password=="1")
{
return true;
}
else
{
return false;
}
}
}
}</span>
三、在Controller中新添加控制器:
如图:
代码例如以下:
<span style="font-family:Microsoft YaHei;font-size:12px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyFirstMvcProject.Controllers
{
public class LoginController : Controller
{
//
// GET: /login/
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public void Index(string username, string password)
{
Models.Login_BS l_bs = new MyFirstMvcProject.Models.Login_BS();
if (l_bs.login(username, password))
{
Response.Write("登陆成功,用户名称为:" + username);
}
else
{
Response.Write("登陆失败");
}
}
}
}
</span>
四、添加视图:
在类LoginController中的方法Index()上单击右键,选择增加视图,如图:
五、改动“Index.aspx,”文件:
系统会在Views目录下加入Login目录,并在当中加入文件“Index.aspx”,改动文件内容。
如图:
代码例如以下:
<span style="font-family:Microsoft YaHei;font-size:12px;"><%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<form action="/login" method="post">
<p>username:<input type="text" name="username" /></p>
<p>密码: <input type="password" name="password" /></p>
<p>
<input type="submit" value="登陆" /></p>
</form>
</div>
</body>
</html>
</span>
六、执行后输入username、密码,成功后会提示输入正确:
如图:
版权声明:本文博客原创文章。博客,未经同意,不得转载。