ASP.NET Core MVC_接受来自客户端的数据


代码

接受来自客户端的数据

接受表单数据——多参数

View
CreateMenu.cshtml

@{
    ViewBag.Title = "创建菜单";
} 
<h2>创建菜单</h2>
<form action="/SubmitData/CreateMenu" method="post">
    <fieldset>
        <legend>Menu</legend>
        <label for="id">Id</label><br />
        <input name="id" id="id" type="number" /><br />
        <label for="text">Text</label><br />
        <input name="text" id="text" type="text" /><br />
        <label for="price">Price</label><br />
        <input name="price" id="price" type="number" step="0.01" /><br />
        <label for="date">Date</label><br />
        <input name="date" id="date" type="date" /><br />
        <label for="category">Category</label><br />
        <input name="category" id="category" type="text" /><br />
        <button type="submit">Submit</button>
    </fieldset>
</form>

这里写图片描述

Index.cshtml

@{
    ViewData["Title"] = "Index";
}
<h2>Index</h2>
@ViewBag.Info

这里写图片描述

Controller

public IActionResult Index()
{
    return View();
}
public IActionResult CreateMenu() => View();

[HttpPost]
public IActionResult CreateMenu(int id, string text, double price, DateTime date, string category) {
    var m = new Menu
    {
        Id = id,
        Text = text,
        Price = price,
        Date = date,
        Category = category
    };
    ViewBag.Info = $"menu created: {m.Text}, Price: {m.Price}, " + $"date: {m.Date}, category: {m.Category}";
    return View("Index");
}

接受表单数据——Model

View(省略Index)

@{
    ViewBag.Title = "Create Menu";
}
<h2>Create Menu</h2>
<form action="/SubmitData/CreateMenu2" method="post">
    <fieldset>
        <legend>Menu</legend>
        <label for="id">Id</label><br />
        <input name="id" id="id" type="number" /><br />
        <label for="text">Text</label><br />
        <input name="text" id="text" type="text" /><br />
        <label for="price">Price</label><br />
        <input name="price" id="price" type="number" /><br />
        <label for="date">Date</label><br />
        <input name="date" id="date" type="date" /><br />
        <label for="category">Category</label><br />
        <input name="category" id="category" type="text" /><br />
        <button type="submit">Submit</button>
    </fieldset>
</form>

Controller

public IActionResult CreateMenu2() => View();

[HttpPost]
public IActionResult CreateMenu2(Menu menu)
{
    ViewBag.Info = $"menu created: {menu.Text}, Price: { menu.Price}, " + $"date: {menu.Date}, category: {menu.Category}";
    return View("Index");
}

接受表单数据——使用不带参数的操作方法将输入数据传递给Model

View(省略Index)

@{
    ViewBag.Title = "Create Menu";
}
<h2>Create Menu</h2>
<form action="/SubmitData/CreateMenu3Result" method="post">
    <fieldset>
        <legend>Menu</legend>
        <label for="id">Id</label><br />
        <input name="id" id="id" type="number" /><br />

        <label for="text">Text</label><br />
        <input name="text" id="text" type="text" /><br />

        <label for="price">Price</label><br />
        <input name="price" id="price" type="number" /><br />

        <label for="date">Date</label><br />
        <input name="date" id="date" type="date" /><br />

        <label for="category">Category</label><br />
        <input name="category" id="category" type="text" /><br />

        <button type="submit">Submit</button>
    </fieldset>
</form>

Controller

public IActionResult CreateMenu3() => View();

/// <summary>
/// 创建了新Menu类实例,
/// 并将此实例传递给Controller基类的TryUpdateModelAsync方法。
/// 如果更新后更新的模型未处于有效状态,则TryUpdateModelAsync返回false
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> CreateMenu3Result()
{
    //创建了新Menu类实例
    var m = new Menu();
    //并将此实例传递给Controller基类的TryUpdateModelAsync方法
    bool updated = await TryUpdateModelAsync<Menu>(m);
    //如果更新后更新的模型未处于有效状态,则TryUpdateModelAsync返回false:
    if (updated)
    {
        ViewBag.Info = $"menu created: {m.Text}, Price: {m.Price}, date: {m.Date.ToShortDateString()}, category: {m.Category}";
        return View("Index");
    }
    else
    {
        return View("Error");
    }
}

注释和验证

使用注解用于在更新数据时进行验证。
Model

public class Menu
{
    public int Id { get; set; }
    [Required, StringLength(50)]
    public string Text { get; set; }
    [Display(Name = "Price"), DisplayFormat(DataFormatString = "{0:C}")]
    public double Price { get; set; }
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }
    [StringLength(10)]
    public string Category { get; set; }
}

可用于验证的attribute类型:

  • CompareAttribute——比较不同的属性
  • CreditCardAttribute——验证有效的信用卡号
  • EmailAddressAttribute——验证电子邮件地址
  • EnumDataTypeAttribute——比较输入与枚举值
  • PhoneAttribute——验证电话号码。

还可以使用其他属性来获取显示和错误消息的值 - 例如,DataTypeAttribute和DisplayFormatAttribute。

要使用验证属性,可以使用ModelState.IsValid验证模型的状态

public IActionResult CreateMenu4() => View();

[HttpPost]
public IActionResult CreateMenu4(Menu menu)
{
    if (ModelState.IsValid)
    {
        ViewBag.Info =
          $"menu created: {menu.Text}, Price: {menu.Price}, date: {menu.Date.ToShortDateString()}, category: {menu.Category}";
    }
    else
    {
        ViewBag.Info = "not valid";
    }
    return View("Index");
}

如果Model为无法更改类型的类

如果使用工具生成的模型类,您可能会认为很难向属性添加属性。

扩展类

由于工具生成的类被定义为部分类,可以通过添加属性和方法,实现其他接口以及实现工具生成的类使用的部分方法来扩展类。

建立新类

如果无法更改类型的源代码,则无法向现有属性和方法添加属性。假设Menu类是工具生成的部分类。 然后,具有不同名称的新类(例如,MenuMetadata)可以定义与实体类相同的属性并添加注释

public class MenuMetadata
{
    public int Id { get; set; }
    [Required, StringLength(25)]
    public string Text { get; set; }
    [Display(Name = "Price"), DisplayFormat(DataFormatString = "{0:C}")]
    public double Price { get; set; }
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }
    [StringLength(10)]
    public string Category { get; set; }
}

MenuMetadata类必须链接到Menu类。 使用工具生成的部分类,可以在同一名称空间中创建另一个部分类型,以将ModelMetadataType属性添加到创建连接的类型定义中(With toolgenerated partial classes, you can create another partial type in the same namespace to add the ModelMetadataType attribute to the type definition that creates the connection)

[ModelMetadataType(typeof(MenuMetadata))]
public partial class Menu
{}

HTML Helper方法还可以使用注释向客户端添加信息。

猜你喜欢

转载自blog.csdn.net/Star_Inori/article/details/82085904