netcore v2-模型綁定的七種用法

/**********************BindingController.cs**********************************/

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

namespace PocoDemo
{
    public class BindingController:Controller
    {
        //一基本類型綁定
        // binding/repeat?text=dino&number=2
        public IActionResult Repeat(string text,int number)
        {
            return Ok(string.Format("text={0} number={1}", text, number));
        }

        //二 強制從給定源綁定
        //binding/visit?city=newyork
        public IActionResult Visit([FromQuery] string city)
        {
            return Ok(city);
        }

        //三 從頭綁定
        //binding/culture
        public IActionResult Culture([FromHeader(Name ="Accept-Language")] string language)
        {
            return Ok(language);
        }

        //四 從請求體綁定
        public IActionResult Print([FromBody] string content)
        {
            return Ok(content);
        }

        //五 綁定複雜類型
        //binding/showperson?name=zs&age=5
        public IActionResult ShowPerson(Person person)
        {
            return Ok(person.Age + "  " + person.Name);
        }

        //六 綁定基本類型的數組
        public IActionResult ShowEmails([Bind(Prefix ="Email")] IList<string> Emails)
        {
            return Ok(string.Join("  ",Emails));
        }

        //七 綁定複雜類型的數組
        public IActionResult ShowPersons( IList<Person> persons)
        {
            return Ok(persons.Count);
        }


    }
}
/*********************************index.cshtml***************************************/

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
<h1>@ViewData.Model.Title</h1>
<form action="/binding/print" target="_self" method="post">
    <input type="text" name="Title" value="C#" />
    <button type="submit">submit</button>
</form>

<form action="/binding/showemails" target="_self" method="post">
    <input type="text" name="Email" id="email1" />
    <input type="text" name="Email" id="email2" />
    <input type="text" name="Email" id="email3" />
    <button type="submit">submit</button>
</form>

<form action="/binding/showpersons" target="_self" method="post">
    <input type="text" name="persons[0].Age" id="age01" />
    <input type="text" name="persons[0].Name" id="name01" />
    <input type="text" name="persons[1].Age" id="age11" />
    <input type="text" name="persons[1].Name" id="name12" />
    <input type="text" name="persons[2].Age" id="age21" />
    <input type="text" name="persons[2].Name" id="name21" />

    <button type="submit">submit</button>
</form>
@{
}
 

發佈了459 篇原創文章 · 獲贊 71 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章