ASP.NET Core2.0项目实战-002

Controller的参数的传递

Url请求

GET: http://www.xxx.com?id=1&name=张三

POST:

(1)http://www.xxx.com

(2)Body 传递form等。

    

这种请求是一种协议,浏览器按照协议传,代码解析

参数传递的实际代码

区别post和get以及frombody或者fromform

using KevinTest001.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace KevinTest001.Controllers
{
    /***
     *#Kevin  asp.net 
     * 
     * asp.net mvc
     * asp.net core mvc
     * 绑定模型机制把获取http的请求的参数 (get,post) action的参数对应的参数进行绑定
     * id参数   index(int id)
     * IBindModel原理底层 
     * ModelState  模型绑定状态
     */
    public class BindController:BaseController
    {
        //localhost:60201/bind/index?id=7&name=张三
        //public IActionResult Index(int id,string name)  #Kevin 多个参数的时候传递比较麻烦
        //public IActionResult Index(Person person)   #Kevin 可以按照Person里面的字段比配传递接收
        //public IActionResult Index([FromBody]Person person)   //#kevin指定只能从页面Body传递,不能从Url来
        
        //默认是get方法
        public IActionResult Index()
        {           
           return View();
        }

        //#支持重载
        /*
        [HttpPost]
        public IActionResult Index([FromForm]Person person)   //http://localhost:60154/bind/index
        {
            return View();
        }
        */

        //#支持重载
        /*
        [HttpPost]
        public IActionResult Index(Person person,List<int> ids)     //获取html页面的列表
        {
            return View();
        }
        */
        [HttpPost]
        public IActionResult Index(Person person)     //获取html页面的列表
        {
            /*
             * if (String.IsNullOrEmpty(person.name))
            {
                return Content("请输入名字");
            }
            */
            ModelState.Remove("name"); //#Kevin 这种就可以去除验证了,使不同页面引用同一模型的时候去掉验证
            bool flag = ModelState.IsValid;  //看前台页面满足模型验证否?
            if (ModelState.IsValid)
            {
                return Content("数据验证不通过");
            }

            return View();
        }


    }
}

数据验证:

数据必须填写之类的

在Model中写

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace KevinTest001.Models
{
    public class Person
    {
        public string id { get; set; }

        //[Required]  //#Kevin 这个是说字段必须填写的
        [Required(ErrorMessage = "请输入名称")]  //#Kevin 错误提示
        [StringLength(2, ErrorMessage = "长度超过2位")]  //#校验长度
        //[EmailAddress],时间、正则表达式验证等
        public string name { get; set; }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值