【问题标题】:Required attribute in action methods argument操作方法参数中的必需属性
【发布时间】:2019-09-05 10:50:49
【问题描述】:

我有一个Controller的动作方法Create如下:

[HttpPost]
public async Task<IActionResult> Create([Required]string name)
{
    if (ModelState.IsValid)
    {
        IdentityResult result = await roleManager.CreateAsync(new IdentityRole(name));
        if (result.Succeeded)
            return RedirectToAction("Index");
        else
            Errors(result);
    }
    return View(name);
}

[Required] 属性在参数中的作用是什么?

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-core-mvc data-annotations


【解决方案1】:

[Required] 属性允许您使用ModelState.IsValid 构造。

基本上它说当标记参数为空时你的模型是无效的。

参考:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1

【讨论】:

  • 如果你在控制器的类上使用 newerAPiController 属性,你就不需要 modelstate.isvalid - 它是为你完成的
【解决方案2】:

[Required] 确保模型得到验证。如果您忽略将名称作为查询字符串发送,则会出现以下错误。

{
"name": [
    "The name field is required."
]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多