登录界面UI
在有一定的Java项目基础上,建议直接开始接触项目学习,在学习和理解的同时,收获一定的成就感,会更加有动力继续的学习下去。
设计
- 建立登录和注册账号的界面,实现前后端数据交互。
- 采用bootstrap加入页面样式
- 开发的基础框架
基础知识
View的存放位置约定:都统一存放在 Views文件夹下
Action Method Selector:应用在Controller的Action上
文中以 [HttpPost] 举例
ViewBag
在View和Controller中传递数据的一种方式 (类似的方式还有ViewData、TempData), 掌握通过ViewBag在View和Controller中传递数据
HtmlHelper
通过View的Html属性调用,文中以Html.BeginForm为例
FirstController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EmptyMVC.Controllers
{
public class FirstController : Controller
{
// GET: First
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
ViewBag.LoginState = "登录前....";
return View();
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Login(FormCollection formcollection)
{
string email = formcollection["inputEmail3"];
string password = formcollection["inputPassword3"];
ViewBag.LoginState = email + "登陆后...";
return View();
}
}
}
[HttpPost] ,表示这个Action只会接受http post请求。ASP.NET MVC提供了Action Method Selector, HttpPost就是其中之一。
HttpPost属性典型的应用场景:
涉及到需要接受客户端窗口数据的时候,创建一个用于接收HTTP Get请求的Action, 用于显示界面, 提供给用户填写数据;
另一个同名Action则应用[HttpPost]属性,用于接收用户发来的数据,完成对应的功能。
打开Login.cshtml, 修改form,为后端接收数据做准备。
先在form标签内增加两个属性action, method。对于form中的method(默认是get),通常情况下, get用于简单的读取数据操作,post用于写数据操作。
Login.cshtml
@{
ViewBag.Title = "Login";
}
<h2>Login</h2>
<div id="loginState">
@ViewBag.LoginState
</div>
<div>
@using (Html.BeginForm("Login", "First", FormMethod.Post, new { @class = "form-horizontal" }))
{
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
}
</div>
使用HtmlHelper动态计算路由地址就是其中的一种方法。
添加下面一句代码,将form中内容放到 {} 中去即可
@using (Html.BeginForm(“login”, “First”, FormMethod.Post)) { }
运行,到浏览器中查看源代码,可以看到生成的源代码和原来一样。
实现动态地址路由。
说明:Index:操作方法的名称,First:控制器的名称,这里就是指FirstController,而对于控制器,后面的Controller可以不写,@FormMethod.Get:定义from的method的值,new { id = “mainForm”, name = “mainForm”,@class=“form-inline mainform”}:指定form的id,name,class属性,因class是Razor语法中的关键字所以要用@来标记。另外,还可以设置路由的参数对象,在此基础上加上new{id=“”}即可,可以为id赋值,如果指定确不赋值则可以实现防止提交链接后面自带参数。在其他htmlHelper方法中如果有object HtmlAttributes参数都可以使用new{属性=“”}的方式对生成的html元素附加属性。本例中为用到id,name等属性。