ASP.NET MVC学习——简陋的登录程序

简陋的登录程序
“约定”大于“配置”

  • Controller放到Controller文件夹中,并且命名方式以XxxController结尾
  • 每个Controller都对应View中的一个文件夹,文件夹的名称跟Controller相同
  • Controller中的方法名都对应一个View(非必须,但是建议这么做)而且View的名字跟Action的名字相同
  • MVC的约定,Action返回View时自动去Views文件夹中搜索其名字与请求的action相同的View,如果没有回去Share文件夹下去搜索。

为什么会默认跳转到Index呢?
在RouterConfig.cs中

routes.MapRoute(
	name: "Default",
	url: "{controller}/{action}/{id}",//Home/Index?...
	defaults: new { 
		controller = "Home", 
		action = "Index", 
		id = UrlParameter.Optional }

设置了默认值,控制器是Home,action是Index

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication4.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();//View()默认返回文件夹下的Index
        }
        public ActionResult Login(string name,string password)//name,pas与html控件的名字相对应
        {
            //return Content("hello mvc");
            if (name == "123" && password == "123")//检查账号密码
            {
                return View("Success");//Success视图
            }
            else
            {
                return View("Error");//Error视图
            }
        }
    }
}

return View()视图可以右键点击View()添加视图。

index中的代码:

<form action="/Home/Login" method="post">
    @*在HomeController的Login()声明了两个变量:name和password
        这里的两个名字一一对应
    *@
    name:<input type="text" name="name" /><br />
    password:<input type="password" name="password" /><br />
    <input type="submit" />
</form>

运行后:
在这里插入图片描述
点击提交后:
在这里插入图片描述

附加:加法器

在HomeController中添加:

public ActionResult CalcAdd(int calc1, int calc2)
        {
            int sum = calc1 + calc2;//calc1,calc2对于html中文本框的名字。
            return Content(sum.ToString());
        }

在Index.cshtml中添加:

<script src="/Scripts/jquery-3.3.1.min.js"></script>
@*如果没在母版视图_Layout中使用script,就要添加上面这一句*@
<script>
            $(function () {
                $('#btnAdd').click(function () {
                    $.post(
                        '@Url.Action("CalcAdd","Home")',
                        $('#form1').serialize(),
                        function (msg) {
                            $('#sum').val(msg);
                            //在name=sum的文本框中输出
                        }
                    );
                });
            });

    </script>

    @*@using (Html.BeginForm("", "", ""))*@
    <form action="/Home/CalcAdd" method="post" id="form1">
        <input type="text" name="calc1" />+
        <input type="text" name="calc2" />
        <input type="button" id="btnAdd" value="" />
        <input type="text" name="sum" id="sum" />
    </form>

在这里插入图片描述

发布了53 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/YUEXILIULI/article/details/98382477