初学MVC的小朋友们在写消息提示框的时候多少有点不习惯。它跟.NET Farmework里多少是有区别的,在.NET Farmework中最常见的消息提示框Response.Write();而在MVC中没有Response.Write()方法向页面输入Script脚本,那么在MVC中怎么解决呢?
以常见的登录为例,与大家分享一下登录失败后,弹出登录失败提示框,跳转到登录页。
创建你的控制器,添加视图
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
public ActionResult ZhuYe()
{
return View();
}
}
在Index页面里只有一个简单的Form表单
<h2>用户登录</h2>
<form action="/Login/ZhuYe" method="post">
用户名:<input id="Text1" name="txtname" type="text" /><br />
密码:<input id="Text2" name="pwd" type="text" /><br />
<input type="submit" name="tijiao" value="登录" />
</form>
action为你表单提交发出的动作,指定到哪一个视图页,在这里给它一个主页面演示效果。
在ZhuYe()控制器里写
//Request["txtname"]是Index视图页input name=txtname输入的值
string name = Request["txtname"];
//同Request["txtname"]
string pwd = Request["pwd"];
//判断输入的账号密码是否正确
if (name=="admin"&&pwd=="123")
{
//向视图页传值,返回视图页
ViewBag.name = name;
ViewBag.pwd = pwd;
return View();
}
else
{
//登录失败提示框
return Content("<script >alert('登录失败');window.open('" + Url.Content("/Login/Index") + "', '_self')</script >", "text/html");
}
mvc消息提示框的语法就是把.NET Farmework中常用的response.write换成Content,页面跳转不是windows.location.href=’’ 而变成了 window.open(’" + Url.Content("/Login/Index") + “’, ‘_self’),Url.Content(” ")里面是你需要跳转的视图页,也就是返回登录视图页。
ZhuYe视图页内容
<body>
<h2>恭喜您登录成功</h2>
<p>用户名:@ViewBag.name</p>
<p>用户名:@ViewBag.pwd</p>
</body>
我们简单的演示一下
只是向大家分享了最简单常用的一种,你学到了嘛?赶快去动手试试吧!